下面的program_pass在Rust中编译。
fn main() {
let mut x = 0;
let mut y = &mut x;
let mut z = &mut y;
let mut last = &mut z;
let mut alt_y = &mut x;
let mut alt_z = &mut alt_y;
z = &mut alt_y; // *last = &mut alt_y;
}下面的program_error没有。
fn main() {
let mut x = 0;
let mut y = &mut x;
let mut z = &mut y;
let mut last = &mut z;
let mut alt_y = &mut x;
let mut alt_z = &mut alt_y;
*last = &mut alt_y; // z = &mut alt_y;
}什么是违反在program_error,而不是在program_pass?刚刚开始,但这确实违背了我对锈病的理解。
发布于 2022-04-12 18:35:51
这是而不是的不一致性,而是意图的行为。
在第一种情况下,不使用可变引用。实际上没有问题,所以生锈编译器是快乐的。
在第二种情况下,生锈编译器会看到可变引用last被取消引用,因此它被视为值访问。正如我们所知,铁锈不允许这两个可变的借款。
参考资料:德夫
来证明我的观点对你的程序有一点微调
fn main() {
let mut x = 0;
let mut y = &mut x;
let mut z = &mut y;
let mut last = &mut z;
let mut alt_y = &mut x;
let mut alt_z = &mut alt_y;
// notice the RHS here assigning
// mutable reference of i32 literal
*last = &mut &mut 4;
// ^ not related to x anyhow
}现在这个错误会揭示问题背后的原因\
error[E0499]: cannot borrow `x` as mutable more than once at a time
--> src/main.rs:7:21
|
3 | let mut y = &mut x;
| ------ first mutable borrow occurs here
...
7 | let mut alt_y = &mut x;
| ^^^^^^ second mutable borrow occurs here
...
11 | *last = &mut &mut 4;
| ------------------- first borrow later used here

https://stackoverflow.com/questions/71846769
复制相似问题