I have the following example code, which is the standard basis of event-driven APIs in other programming languages, but in Rust the borrow checker blocks it with "cannot borrow p1
as mutable more than once at a time":
struct Pen {
color_cmyk: u32,
ink: usize,
}
impl Pen {
pub fn new() -> Pen {
Pen {
color_cmyk: 0x80800000,
ink: 20000,
}
}
pub fn write(&mut self, text: &str) -> bool {
if self.ink < text.len() {
return false;
}
self.ink -= text.len();
true
}
}
fn main() {
println!("Hello, world !");
let mut p1 = Pen::new();
p1.write("Hello");
println!("ink: {}, color: {}", p1.ink, p1.color_cmyk);
let mut cb = |text| if p1.write(text) {
println!("{}", text);
} else {
println!("Out of ink !");
};
let mut cb2 = |text| {
p1.write(text);
p1.ink
};
cb("Hello");
cb("World");
println!("{}", cb2("Hello"));
}
error[E0499]: cannot borrow `p1` as mutable more than once at a time
--> src/main.rs:37:23
|
31 | let mut cb = |text| if p1.write(text) {
| ------ -- previous borrow occurs due to use of `p1` in closure
| |
| first mutable borrow occurs here
...
37 | let mut cb2 = |text| {
| ^^^^^^ second mutable borrow occurs here
38 | p1.write(text);
| -- borrow occurs due to use of `p1` in closure
...
45 | }
| - first borrow ends here
The code can be used, for example, to implement two callbacks to a window: one for handling keyboard events and another for handling mouse events, both of which update the window state (ex: changing color, closing the window, etc.).
I know that this question appears elsewhere in Stack Overflow and other forums, but in general, the answers focus on describing the reason of the problem and rarely propose a complete general solution for it:
- Cannot borrow `x` as mutable more than once at a time
- How to bypass “cannot borrow as mutable more than once”?
- Cannot borrow as mutable more than once at a time
- Passing mutable context into callbacks
- Creating a callback system using closures
- Execute callbacks like as mutable borrowing from cycle
- Callback to mutable self