Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I call next_back() on a Split? [duplicate]

Tags:

rust

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"?

like image 647
Michael Dorst Avatar asked Oct 16 '25 14:10

Michael Dorst


1 Answers

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.

like image 196
Denys Séguret Avatar answered Oct 19 '25 00:10

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!