The value does not live long enough with an obvious lifetime, but lives long enough in the absence of

I have the following Rust program that passes a closure to a generic function over a lifetime and a closure of type F that causes a closure with reference to some local data:

 fn other_function<'a, F>(f: F) where F: Fn(&'a u32) { let the_value = 0; f(&the_value); } fn main() { other_function(|_| { /* do nothing */ }); } 

This cannot be compiled with the following messages:

 <anon>:5:8: 5:17 error: `the_value` does not live long enough <anon>:5 f(&the_value); ^~~~~~~~~ <anon>:3:1: 6:2 note: reference must be valid for the lifetime 'a as defined on the block at 3:0... <anon>:3 { <anon>:4 let the_value = 0; <anon>:5 f(&the_value); <anon>:6 } <anon>:4:23: 6:2 note: ...but borrowed value is only valid for the block suffix following statement 0 at 4:22 <anon>:4 let the_value = 0; <anon>:5 f(&the_value); <anon>:6 } error: aborting due to previous error playpen: application terminated with error code 101 

My minimal example might be a little too minimal, since for this example, a valid solution is to remove 'a, and 'a . However, I have a similar situation in a more complex program, in which obvious lifetimes seem.

Is there a way to specify a lifetime manually so that the above program will be accepted by the compiler?

+5
source share
1 answer

The problem is that the other_function gets a lifetime choice that will populate 'a , but you want other_function execute it. You could use a bit of syntax called earlier attribute ratings:

 fn other_function<F>(f: F) where F: for <'a> Fn(&'a u32) { let the_value = 0; f(&the_value); } fn main() { other_function(|_| { /* do nothing */ }); } 

As you pointed out, in this case it makes sense to completely omit 'a . Your case may need something more complex, but nothing makes sense with your example. The caller cannot specify a lifetime that will be compatible with the variable assigned by the stack inside the method you are calling.

+6
source

Source: https://habr.com/ru/post/1233556/


All Articles