i'm trying to share &mut self with the loop and tx closure at the same time and i occurred a "error: lifetime may not live long enough" error
pub fn run(&mut self) {
// Initialize
utils::hide_cursor();
crossterm::terminal::enable_raw_mode().unwrap();
utils::clear();
let app = Arc::new(Mutex::new(self));
let app_thread = Arc::clone(&app);
let tx = &move |command: Command| match command {
Command::Render(tick) => {
let mut data = app_thread.lock().unwrap();
data.render(tick);
drop(data);
}
Command::Exit => {
crossterm::terminal::disable_raw_mode().unwrap();
utils::clear();
utils::show_cursor();
} // Ect (more commands later)
};
tx(Command::Render(0));
loop {
{
let mut data = app.lock().unwrap();
data.element.update(tx, key::read_key());
}
tx(Command::Render(0));
}
}
error: lifetime may not live long enough
--> src/lib.rs:98:37
|
72 | pub fn run(&mut self) {
| - let's call the lifetime of this reference `'1`
...
98 | data.element.update(tx, key::read_key());
| ^^ cast requires that `'1` must outlive `'static`
normal thread needs 'static, if you want to pass data with a lifetime between threads, you must use the scoped threads API.
I don't how your app works, but guessing from the compile error message, it seems this data.element.update() call requires 'static for its argument, probably sending data to different threads. if you cannot rewrite the threading code using the scoped API, then you cannot send a borrowed self to other threads. but it might be possible if you can rewrite this run() method to take a Arc<Self> as the receiver argument self.
side note: even if you managed to send an Arc<&mut Self> to different thread, it probably won't work as you expected, because it would downgrade to a shared reference (i.e. not mut anymore). so you really should re-think your app's architecture, not to fight the borrow check (and the type system as a whole).
yeah, if you want to have a value shared and mutated by multiple threads, you usually either want to stick it in an Arc<Mutex<T>>, or just an Arc, and wrap the indivitual fields in mutexes.