I'm currently learning Rust and I have been struggling for some time with closures. What I'm trying to do is to create an instance of Terminal
, pass it inside a closure and then return that Terminal
instance.
Here's the code:
/// Initialize the screen
fn init_screen() -> Terminal {
let mut terminal = Terminal::init();
terminal.enable_raw_mode();
terminal.enter_alternate_screen();
terminal.clear();
terminal.move_cursor(0, 0);
terminal.hide_cursor();
terminal.enable_mouse();
terminal.event_handler.register_key(
KeyCode::Esc,
Box::new(|_| {
terminal.clear();
})
);
terminal
}
Now this is something that would work without problems had it been TypeScript for example but I'm having problems implementing this in Rust because of the ownership and mutability rules.
How would this pattern be implemented in Rust?
Edit:
The error I receive from the compiler is this:
error[E0499]: cannot borrow `terminal.event_handler` as mutable more than once at a time
--> /home/silvio/Programming/Projects/rustier/src/lib.rs:30:5
|
30 | / terminal.event_handler.register_key(
31 | | KeyCode::Esc,
32 | | Box::new(|_| {
| | - --- first mutable borrow occurs here
| |_________|
| ||
33 | || // let ref_terminal = *terminal.borrow_mut();
34 | || terminal.clear();
| || -------- first borrow occurs due to use of `terminal` in closure
35 | || // ref_terminal.disable_mouse();
... ||
40 | || std::process::exit(0);
41 | || })
| ||__________- cast requires that `terminal` is borrowed for `'static`
42 | | );
| |_____^ second mutable borrow occurs here