Beards do not own what they point to. Your problem is that you borrow a temporary one, which will cease to exist immediately after borrowing it, because you do not store it anywhere. If this helps, consider that borrowing does not matter, they take up storage, and temporary only has temporary storage.
If you want borrowing to last something for any given period of time, you must borrow storage facilities that will last at least for a long time. In this case, since you want to keep the loan in Vec , this means that any storage that you borrow must also survive Vec . In this way:
fn main () { let closure; let mut list: Vec<&Fn() -> i32> = Vec::new(); { closure = || 1; list.push(&closure); } }
Note that closure is defined before list . In Rust, values ββare lost in the reverse lexical order at the end of their area, so any variable defined after list will necessarily be dropped before it, which will lead to a list containing invalid pointers.
If you want to press multiple closures, you will need a separate variable for each of them.
To prevent a possible βmy actual problem is not simpleβ adding (: P): f you need to return list or somehow save it outside of one function call, please note that there is no way to extend the loan. In this case, you need to change list to a vector belonging to short circuits (i.e. Vec<Box<Fn() -> i32>> ).
source share