There are already a lot of threads on this topic but I fail to see if the discussed problems apply to my specific problem.
I have a structure that stores a name
and a callback
function. Stripped down to the problem it looks like this:
pub struct Command<'a> {
name: &'a str,
callback: &'a Fn(&[&str]) -> ()
}
impl <'a> Command<'a> {
pub fn new(name: &'a str, callback: &'a Fn(&[&str]) -> ()) -> Command<'a> {
Command {
name: name,
callback: callback
}
}
}
What I want to do is store a callback function associated with a name (and prob. more stuff in the future).
But when I try to use this bit of code like so:
fn main() {
let play_callback = |args| {
println!("Playing something.");
for arg in args {
println!("{}", arg);
}
};
let play_command = Command::new("play", &play_callback);
}
I get the following error message:
src/main.rs:22:42: 22:56 error: type mismatch resolving `for<'r, 'r> <[closure@src/main.rs:16:22: 21:3] as std::ops::FnOnce<(&'r [&'r str],)>>::Output == ()`:
expected bound lifetime parameter ,
found concrete lifetime [E0271]
src/main.rs:22 let play_command = Command::new("play", &play_callback);
^~~~~~~~~~~~~~
I tried to inline the closure like this
fn main() {
let play_command = Command::new("play", &|args| {
println!("Playing something.");
for arg in args {
println!("{}", arg);
}
});
}
but then I get another error
src/main.rs:16:47: 21:7 error: borrowed value does not live long enough
which I believe I understand why I get.
I tried using a generic type parameter for Command
before switching to a function reference first to store in my Command
structure, but when I wanted to initialize a HashSet
of command objects like this:
let mut commands: HashSet<Command> = HashSet::new();
the compiler wanted me to specify the generic parameter which I think I cannot do as that would mean I could only store the same closure in all my Command
objects.
So my question would be: How can I achieve what I want and what is the best way to do so (and why)?