I have the next code:
pub struct Sender<'a> {
event_callback: Box<dyn FnMut(Event) + 'a>,
}
impl<'a> Sender<'a> {
pub fn new(callback: impl FnMut(Event) + 'a) -> Self {
Sender { event_callback: Box::new(callback) }
}
pub fn send_event(&mut self, event: Event) {
(self.event_callback)(event);
}
}
pub struct Listener<'a> {
my_bool: bool,
sender: Option<Sender<'a>>,
}
impl<'a> Listener<'a> {
pub fn new() -> Self {
let mut listener = Listener { sender: None, my_bool: false };
listener.create_sender();
listener
}
fn create_sender(&'a mut self) {
self.sender = Some(
Sender::new( |event|
match event.event_type() {
EventType::SomeType => self.my_bool = true,
_ => (),
}
)
);
}
}
Issues are:
- Listeners
new
function does not compile:
- E0515: cannot return value referencing local variable
listener
- E0505: cannot move out of
listener
because it is borrowed
I don't really understand the reason why it wouldn't compile.
- If it would compile, there's still this annoying Option<Sender<'a>> which I don't really need because I create Sender immediately after creating listener.
Ideally I would want to write something like this:
pub fn new() -> Self {
Listener { window: self.create_sender(), my_bool: false };
}
How do I implement it? Are there better ways than what I'm trying to do?