I tried this code:
fn main() {
let mut zero = &mut 0;
let mut one = 1;
{
let mut _r = &mut zero;
let mut y = &mut one;
_r = &mut y;
}
println!("{}", one); // compiler complains that there's a mutable reference.
println!("{}", zero);
}
I expected to see this happen: print 1 then 0.
Instead, this happened: compile error
Meta
rustc --version --verbose:
rustc 1.42.0 (b8cedc004 2020-03-09)
binary: rustc
commit-hash: b8cedc00407a4c56a3bda1ed605c6fc166655447
commit-date: 2020-03-09
host: x86_64-pc-windows-msvc
release: 1.42.0
LLVM version: 9.0
Backtrace
error[E0502]: cannot borrow `one` as immutable because it is also borrowed as mutable
--> src\main.rs:11:20
|
7 | let mut y = &mut one;
| -------- mutable borrow occurs here
...
11 | println!("{}", one);
| ^^^ immutable borrow occurs here
12 | println!("{}", zero);
| ---- mutable borrow later used here
EDIT: Here's a concise version of the original snippet which produces the same error:
fn main() {
let mut v1 = &mut 0;
let mut v2 = 1;
{
let mut x = &mut &mut v2;
x = &mut v1;
}
println!("{}", v2); // compiler would complain there's a mutable reference.
println!("{}", v1);
}
it is weird since the buggy behavior depends on the access order between the variables v1 and v2, if change the order or access only one of the two variables, the compiler error disappears
I tried this code:
I expected to see this happen: print 1 then 0.
Instead, this happened: compile error
Meta
rustc --version --verbose:Backtrace
EDIT: Here's a concise version of the original snippet which produces the same error:
it is weird since the buggy behavior depends on the access order between the variables v1 and v2, if change the order or access only one of the two variables, the compiler error disappears