Lifetime error with iterators and closures


#1

I made a small playground program:
https://play.rust-lang.org/?gist=43c75280af902fbcab6c0d344752dba0&version=stable&backtrace=0

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?


#2

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?


#3

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:
https://is.gd/v6tmEM

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.


#4

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.