Why rust use Iterator::find to find item failed and Iterator::position work

 fn find<P>(&mut self, predicate: P) -> Option<Self::Item>
    where
        Self: Sized,
        P: FnMut(&Self::Item) -> bool,
    
fn position<P>(&mut self, predicate: P) -> Option<usize>
    where
        Self: Sized,
        P: FnMut(Self::Item) -> bool,

two method signature is same but

use Iterator::find it doesn't work

    let worker = github_metadata
            .iter()
            .find(|c| c.owner == id.owner && c.repo == id.repo)
            .unwrap();

error

error[E0521]: borrowed data escapes outside of associated function
   --> post_processing/src/manager.rs:234:22
    |
210 |           github_metadata: &[RepoMetadata],
    |           ---------------  - let's call the lifetime of this reference `'1`
    |           |
    |           `github_metadata` is a reference that is only valid in the associated function body
...
234 |           let worker = github_metadata
    |  ______________________^
235 | |             .iter()
236 | |             .find(|c| c.owner == id.owner && c.repo == id.repo)
    | |                                                               ^
    | |                                                               |
    | |_______________________________________________________________`github_metadata` escapes the associated function body here
    |                                                                 argument requires that `'1` must outlive `'static`
    |
    = note: requirement occurs because of a mutable reference to `std::slice::Iter<'_, RepoMetadata>`
    = note: mutable references are invariant over their type parameter
    = help: see <https://doc.rust-lang.org/nomicon/subtyping.html> for more information about variance


  

it works, I use Iterator::position method can

let idx = github_metadata
            .iter()
            .position(|c| c.owner == id.owner && c.repo == id.repo)
            .unwrap();
let worker = github_metadata[idx];

It probably has to do with what you want to return from a function (possibly annotated with an erroneous lifetime annotation). Please provide complete code, preferably a playground that reproduces the error.

worker has different types in the two snippets.

    // `&RepoMetadata` (borrowed from `github_metadata`)
    let worker = github_metadata
            .iter()
            .find(|c| c.owner == id.owner && c.repo == id.repo)
            .unwrap();
let idx = github_metadata
            .iter()
            .position(|c| c.owner == id.owner && c.repo == id.repo)
            .unwrap();
// `RepoMetadata` (copied out of `github_metadata`)
let worker = github_metadata[idx];
3 Likes

thanks, I know error

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.