Why can I not reverse the result of str::split?

前端 未结 3 942
太阳男子
太阳男子 2021-01-19 06:04

According to the docs for Split, there is a rev method on the result of doing split on a string:

fn main() {
    let mut length = 0;         


        
3条回答
  •  天涯浪人
    2021-01-19 06:11

    TLDR: StrSearcher (the type that does searching for string patterns) doesn't implement DoubleEndedSearcher and, as such, the split iterator doesn't implement DoubleEndedIterator and, as such, you can't call rev on it.

    If you look at the documentation on that page for rev, you'll see where Self: DoubleEndedIterator. This means that rev is defined if and only if the type the Iterator trait is being implemented for (which is Split) also has an implementation of the DoubleEndedIterator trait.

    If you look further down, you'll see:

    impl<'a, P> DoubleEndedIterator for Split<'a, P>
    where P: Pattern<'a>, P::Searcher: DoubleEndedSearcher<'a>
    

    Thus, DoubleEndedIterator is implemented for Split if and only if both of those conditions are satisfied: P must be a Pattern and the Searcher type it defines must implement DoubleEndedSearcher.

    Now, you're using a string literal as the pattern, so if you check the documentation for the str type, you'll see:

    impl<'a, 'b> Pattern<'a> for &'b str
    

    Within that, the associated Searcher type is defined as:

    type Searcher = StrSearcher<'a, 'b>
    

    Nearly there! Follow the link to the documentation for StrSearcher and...

    ...there's no implementation of DoubleEndedSearcher. Thus, the required bounds are not satisfied and rev can't be used on the Split iterator.

提交回复
热议问题