Your code works just fine if you delete all annotations for life and allow the compiler to do its job:
struct Provider; impl Provider { fn get_string(&self) -> &str { "this is a string" } } fn main() { let provider = Provider; let mut vec = Vec::new(); let mut fun = |s| { vec.push(s); }; fun(provider.get_string()); }
In short, there is no way to explicitly refer to the lifetime of a local variable, only function arguments. The compiler knows how to do this.
If you really need it, you can create a function to annotate the lifetime:
fn thing<'a>(provider: &'a Provider) -> Vec<&'a str> { let mut vec: Vec<&'a str> = Vec::new(); { let mut fun = |s: &'a str| vec.push(s); fun(provider.get_string()); } // End mutable borrow of `vec` vec } fn main() { let provider = Provider; thing(&provider); }
Why did the original annotations stop working?
In particular, this is a bit:
let fun = |s: &str| { vec.push(s); };
This announces a new lifetime at closing. Using the prepared syntax (you cannot declare lifetimes with closing arguments ), this will be equivalent to:
let fun = <'a> |s: &'a str| { vec.push(s); };
This is why the compiler has an error:
life time cannot survive the anonymous life time # 1 defined on the [block circuit]
There is no connection between the generated lifetime and the Provider
. Leaving this, the compiler can insert the desired, but not verifiable, lifetime.
source share