I'm really stuck trying to work code similar to the following:-
pub struct StructWithCallback<'a, C: Fn(u16, &'a str, &'a str) -> u16>
{
some_data: u16,
first_name: String,
last_name: String,
callback: C,
}
impl<'a, C: Fn(u16, &str, &str) -> u16> StructWithCallback<'a, C>
{
fn do_something_with_callback(&self) -> u16
{
(self.callback)(self.some_data, &self.first_name, &self.last_name)
}
}
fn sample_callback<'b>(some_data: u16, first_name: &'b str, last_name: &'b str) -> u16
{
45
}
fn main()
{
let x = StructWithCallback
{
some_data: 16,
first_name: "Hello".to_string(),
last_name: "World".to_string(),
callback: sample_callback,
};
x.do_something_with_callback()
}
Of course, this doesn't work; rustc complains that the lifetime 'a
is unused in the fields of the struct. True. It's used to define the callback definition, C
. If one completely removes 'a
from this code, then the lifetimes of first_name
and last_name
are no longer linked. How do I tell rustc that the lifetimes are linked. I want to be able to supply both functions and closures as the value of StructWithCallback.callback