Considering following code
fn foo<F>(f:Box<F>)->Box<FnMut()->i32>
where F:Fn()->i32+'static ///why F is required to be 'static? remove it and the compile will complain
{
let result=Box::new(move||{ //f is captured by move here
f()
});
result
}
fn bar()->Box<FnMut()->i32>{
foo(Box::new(||{1}))
}
fn main() {
let mut ff=bar();
println!("{}",ff())
}
The generic parameter F is required to be 'static.
My questions are:
-
The input parameter
f
of functionfoo
is boxed and captured by the inner closureresult
with themove
keyword, why its typeF
(actuallyBox<F>
) is required to be'static
? It is passed by value and it is moved into the closureresult
, i.e., its ownership is transferred into theresult
, why its lifetime has to be'static
? -
In above code, the function
foo
is called in the functionbar
, then the input parameter offoo
is apparently stack allocated, the lifetime of which is obviously not'static
, but above program can be compiled and run, why? What does the'static
mean in above program?