inspect
is a closure that takes an immutable reference to ball
.
edit
is a closure that takes a mutable reference to ball
.
I know that the borrow checker doesn't let you borrow at all while a mutable borrow is around.
My expectation however is that once edit
, which is the only "source" of mutable borrows goes out of scope, I should be able to call inspect
again.
Not so, apparently? Or am I getting something wrong about the closures' lifetimes?
Given that
#[derive(Default, Debug)]
pub struct Ball {
pub color: String,
pub size: String,
}
pub fn moves() {
let mut ball = Ball {
color: "blue".to_string(),
size: "small".to_string(),
};
let inspect = || {
println!("Unremarkable. {} ball. ", (&ball).color); // &ball
};
inspect(); // OK.
{
let mut edit = || {
ball.color = "red".to_string(); // Not OK if I call inspect later.
};
edit()
}; // <---- I expect edit to go out of scope here
inspect(); // If I comment this out edit doesn't complain.
}
The error I'm getting is
error[E0502]: cannot borrow `ball` as mutable because it is also borrowed as immutable
--> src/moves.rs:40:25
|
34 | let inspect = || {
| -- immutable borrow occurs here
35 | println!("Unremarkable. {} ball. ", ( &ball ).color);
| ---- first borrow occurs due to use of `ball` in closure
...
40 | let mut edit = || {
| ^^ mutable borrow occurs here
41 | ( &mut ball ).color = "red".to_string()
| ---- second borrow occurs due to use of `ball` in closure
...
45 | inspect();
| ------- immutable borrow later used here
For more information about this error, try `rustc --explain E0502`.
error: could not compile `nightmoves` due to previous error
What am I missing?