All of the three alternatives in the following code give the error "closure may outlive current function" for each of the closures called process
. Can someone explain the reason why all of them outlive the current function main
?
type MyFn = FnMut();
trait DoesWork {
fn work(&self, f: &mut MyFn);
}
struct Abc;
impl DoesWork for Abc {
fn work(&self, f: &mut MyFn) {
for _ in 0..5 {
f();
}
}
}
impl Abc {
fn work_no_env(f: &mut MyFn) {
for _ in 0..5 {
f();
}
}
}
fn global_work_no_env(f: &mut MyFn) {
for _ in 0..5 {
f();
}
}
fn main() {
let mut v = Vec::<String>::new();
{
let mut process = || {
v.push("A".to_string());
};
global_work_no_env(&mut process);
}
{
let mut process = || {
v.push("A".to_string());
};
Abc::work_no_env(&mut process);
}
{
let abc = Abc{};
let mut process = || {
v.push("A".to_string());
};
abc.work(&mut process);
}
println!("v={:?}", v);
}