Lifetime error with iterators and closures


I made a small playground program:

If I understand correctly, the problem is that the iterator returned from the iter() function can only live in the closure, but it will be used by the next() function after the double_all has completed.
How can I solve this?


In your particular example, you can capture asd directly in the closure (and invoke the closure without any args), and let the compiler associate the lifetimes. But, I suspect your question is probably about something more general?


Refactoring the code a little could work.
I think the closure would need a lifetime parameter to make this work without refactoring, but only fn functions can have lifetime parameters AFAIK.

This is the same error:

I realized iref_fn only works because of lifetime elision, but lifetime elision doesn’t apply to closures, so the iref won’t have a lifetime parameter.


This also works:

    let iref: &(for<'a> Fn(&'a S) -> &'a i32) = &|s| &s.i;

but there’s no similar way to annotate the type without using a trait object. I believe this is issue #22340.