This code does not compile:
struct Signal<T> {
handlers: Vec<Box<dyn Fn(&T)>>,
}
impl<T> Signal<T> {
fn emit(&mut self, data: &T) {
for handler in &self.handlers {
handler(data);
}
}
}
struct Message<'a, T> {
data: &'a T,
}
fn main() {
let mut signal = Signal { handlers: Vec::new() };
let data = 0; // can be any arbitrary data
signal.emit(&Message { data: &data }); // error: borrowed value does not live long enough
}
signal
is a Signal<Message<'a, i32>>
, where 'a
must last as long as signal
. Can I somehow constrain 'a
to the smallest possible lifetime, so it only lasts for each call to emit()
? I'm trying to get a similar outcome to Fn(&T)
, where &T
has the smallest possible lifetime.
What I really want is the type for<'a> Signal<Message<'a, i32>>
, but of course Message
is not a trait so that's not possible. Is it possible to express this some other way?