letmut x = 1; let y = &mut x; let z = &mut x; x = 2; *y = 3; *z = 4; println!("{}", x); # will get error: # error[E0499]: cannot borrow `x` as mutable more than once at a time # --> src/main.rs:5:9 # | # 4 | let y = &mut x; # | ------ first mutable borrow occurs here # 5 | let z = &mut x; # | ^^^^^^ second mutable borrow occurs here # 6 | x = 2; # 7 | *y = 3; # | ------ first borrow later used here
# error[E0506]: cannot assign to `x` because it is borrowed # --> src/main.rs:6:1 # | # 4 | let y = &mut x; # | ------ `x` is borrowed here # 5 | let z = &mut x; # 6 | x = 2; # | ^^^^^ `x` is assigned to here but it was already borrowed # 7 | *y = 3; # | ------ borrow later used here
这个时候就是内部可变性发挥作用的时候了。拿Cell来举例
1 2 3 4 5 6 7
let x = Cell::new(1); let y = &x; let z = &x; x.set(2); y.set(3); z.set(4); println!("{}", x.get());