Usually, an immutable &mut
can be used to mutate the data it refers to:
fn main() {
let mut v = vec![];
let r = &mut v; // r itself is immutable
r.push(0); // an immutable &mut is used to mutate v
println!("{:?}", v);
}
However, when I attempt to take a &
to the &mut
, the code no longer compiles:
fn main() {
let mut v = vec![];
let r = &mut v;
let rr = &r; // &&mut
rr.push(0); // use a &&mut to mutate the data
println!("{:?}", v);
}
error[E0596]: cannot borrow `**rr` as mutable, as it is behind a `&` reference
--> src/main.rs:6:5
|
5 | let rr = &r;
| -- help: consider changing this to be a mutable reference: `&mut r`
6 | rr.push(0);
| ^^ `rr` is a `&` reference, so the data it refers to cannot be borrowed as mutable
error: aborting due to previous error
For more information about this error, try `rustc --explain E0596`.
error: could not compile `playground`.
To learn more, run the command again with --verbose.
The code can be fixed by making r
mut
and taking a &mut
to r
instead of a &
.
This observation bewilders me, a Rust beginner. In my understanding, the result of dereferencing a &
can be used in the some ways as a non-mut
variable can. Is this somehow related to reborrowing? Can you please indicate the errors in my thought process and help me understand? Thank you.