3

The documentation for Split says that it implements DoubleEndedIterator which is supposed to have a next_back() method which gets the last element.

But when I do this:

fn get_file_ext(file_name: &str) -> Option<String> {
    if let Some(ext) = file_name.split(".").next_back() {
        return Some(ext.to_owned());
    }
    None
}

I get this error:

error[E0599]: no method named `next_back` found for struct `std::str::Split<'_, &str>` in the current scope
   --> src/lib.rs:2:45
    |
2   |       if let Some(ext) = file_name.split(".").next_back() {
    |                                               ^^^^^^^^^ method not found in `std::str::Split<'_, &str>`
    |
    = note: the method `next_back` exists but the following trait bounds were not satisfied:
            `std::str::pattern::StrSearcher<'_, '_>: std::str::pattern::DoubleEndedSearcher<'_>`
            which is required by `std::str::Split<'_, &str>: std::iter::DoubleEndedIterator`

What does it mean by "the following trait bounds were not satisfied"?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Michael Dorst
  • 8,210
  • 11
  • 44
  • 71

1 Answers1

7

Solution

Replace

file_name.split(".")

with

file_name.split('.')

Explanation

Here's the trait implementation declaration:

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

The missing trait bound here is

<P as Pattern<'a>>::Searcher: DoubleEndedSearcher<'a>,

This trait bound is implemented for the searcher of char but not for &str.

See DoubleEndedSearcher

char::Searcher is a DoubleEndedSearcher because searching for a char only requires looking at one at a time, which behaves the same from both ends.

(&str)::Searcher is not a DoubleEndedSearcher because the pattern "aa" in the haystack "aaa" matches as either "[aa]a" or "a[aa]", depending from which side it is searched.

Said otherwise: Not all patterns allow double ended search. A char allows it but not a string.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • Thank you! Those type annotations in the documentation make a lot more sense after reading your answer. – Michael Dorst Sep 08 '19 at 06:47
  • @Shepmaster could you point me to where I can learn more about what `

    ` means? Are the `<>` syntactical sugar or do they have a meaning?

    – financial_physician Mar 17 '22 at 20:39
  • @financial_physician [The book covers the syntax](https://doc.rust-lang.org/book/appendix-02-operators.html). The syntax means "treat type `P` as the trait `Pattern`". – Shepmaster Mar 29 '22 at 17:48