Hey there, in the example bellow I'm trying to pass a closure to a method and store it in a Vec:
struct Container {
actions: Vec<Box<dyn Fn() -> String>>,
}
impl Container {
fn new() -> Self {
Self { actions: Vec::new() }
}
fn add<F: Fn() -> String>(&mut self, f: F) {
self.actions.push(Box::new(f));
}
}
Bu then I get this error:
error[E0310]: the parameter type `F` may not live long enough
--> src/main.rs:19:25
|
19 | self.actions.push(Box::new(f));
| ^^^^^^^^^^^ ...so that the type `F` will meet its required lifetime bounds
|
help: consider adding an explicit lifetime bound...
|
18 | fn add<F: Fn() -> String + 'static>(&mut self, f: F) {
| +++++++++
For more information about this error, try `rustc --explain E0310`.
error: could not compile `playground` due to previous error
However, the code bellow works:
fn main() {
let f = || "A String".to_owned();
let mut v: Vec<Box<dyn Fn() -> String>> = Vec::new();
v.push(Box::new(f));
println!("{}", v[0]());
}
So what am I missing here ?