根据 Rust 手册,我们不能同时使用变量作为可变和不可变引用。
但由于某种原因,当我尝试使用u32类型执行此操作时,它不会抛出任何错误。
fn main() {
let mut num = 69;
do_something(&mut num); // no error
dont_do_anything(&num); // no error
println!("{}", num);
}
fn dont_do_anything(num: &u32) {
println!("{}", num);
}
fn do_something(num: &mut u32) {
*num += 1;
}
Run Code Online (Sandbox Code Playgroud)
我在这里错过了什么吗?
你不是同时经过它们,而是一个接一个地经过它们。
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.
}
Run Code Online (Sandbox Code Playgroud)
由于任何借用之间不会发生重叠,因此不会违反任何借用规则。现在让我们看看哪些是被禁止的:
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);
}
Run Code Online (Sandbox Code Playgroud)
这段代码确实同时使用了可变借用和不可变借用(我们调用的行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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
334 次 |
| 最近记录: |