可变的借用不一致
以下program_pass在生锈中编译。
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中? 刚刚开始,但这确实与我认为是我对锈蚀的理解有关。
The following program_pass compiles in 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;
}
The following program_error does not.
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;
}
What is violated in program_error, while not in program_pass?
Just started, but this is really going against what I thought to be my understanding of Rust.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
不是不一致,它是预期的行为。
在第一种情况下,没有使用可变的参考。实际上没有问题,因此生锈的编译器很高兴。
在第二种情况下,Rust编译器认为可变参考
最后
被删除,因此将其作为价值访问。众所周知,Rust不允许两个可变的借款。参考: deref
证明我的观点已经调整了您的计划位
和现在的错误将揭示问题背后的原因\
It's not inconsistency, it is is a intended behavior instead.
In first case, no mutable reference is being used. Effectively no issue, so rust compiler is happy.
In second case the rust compiler sees that mutable reference
last
is being dereferenced so it is taken as value access. And as we know rust doesn't allow the two mutable borrows.Reference: Deref
To prove my point have tweaked your program a bit
And now the error will reveal the reason behind the issue\