How to get a `Iterator<Item = &'a Foo>` from `Vec<Arc<Foo>>`

I have a function with take a iterator of Foo:

fn bar<'a, I:Iterator<Item = &'a Foo>,>(iter: I) {}

and It works fine when using like this:

    let vec = vec![Foo::new(); 3];

but now the type of vec changes to Vec<Arc<Foo>>, I tried to create a new vector which safe references of Foo to feed bar:

    let mut vec2 : Vec<&Foo> = vec::new();
    vec.iter().for_each(|item| {

but the item type of vec2.iter() is &&Foo, not &Foo, which do not meet the parameter in bar.

I tried for hours but didn't find a way.

Since I can't change the signature of bar(), any way I can feed a Vec<Arc<Foo>> to it?

Apart from the fact that allocating an intermediate vector is unnecessary, you can rely on smart pointers implementing Deref, so you can just call it like this (Playground):

1 Like

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.