你不是同时超过他们,你是一个接一个地超过他们.
fn main() {
let mut num = 69;
// at the following line you start to borrow num mutably
do_something(&mut num);
// but the mutable borrow is only used in the line above
// at the following line you start a shared borrow of num
dont_do_anything(&num);
// and you only use the shared borrow in the line above.
// then you do another shared borrow for `pritnln`
println!("{}", num);
// which is used just in the one line again.
}
由于任何borrow 之间都不会发生重叠,因此没有违反任何borrow 规则.
现在让我们来看看一些不被允许的事情:
fn main() {
let mut num = 69;
// start mutably borrowing
let mut_num = &mut num;
// try to borrow immutably after we started a mutable borrow, but before we stopped using it
dont_do_anything(&num);
// use the mutable borrow here
do_something(mut_num);
}
这段代码确实同时使用了可变和不可变的借入(我们调用dont_do_anything
的那一行),因此编译器会对我们大喊大叫:
Compiling playground v0.0.1 (/playground)
error[E0502]: cannot borrow `num` as immutable because it is also borrowed as mutable
--> src/main.rs:6:22
|
4 | let mut_num = &mut num;
| -------- mutable borrow occurs here
5 | // try to borrow immutably after we started a mutable borrow, but before we stopped using it
6 | dont_do_anything(&num);
| ^^^^ immutable borrow occurs here
7 | // use the mutable borrow here
8 | do_something(mut_num);
| ------- mutable borrow later used here