我正在学习《Rust by Example》并运行来自“别名”页的代码:
struct Point {
x: i32,
y: i32,
z: i32,
}
fn main() {
let mut point = Point { x: 0, y: 0, z: 0 };
{
let borrowed_point = &point;
let another_borrow = &point;
// Data can be accessed via the references and the original owner
println!(
"Point has coordinates: ({}, {}, {})",
borrowed_point.x, another_borrow.y, point.z
);
// Error! Can't borrow point as mutable because it's currently
// borrowed as immutable.
let mutable_borrow = &mut point;
println!(
"Point has coordinates: ({}, {}, {})",
mutable_borrow.x, mutable_borrow.y, mutable_borrow.z
);
let mutable_borrow2 = &mut point;
println!(
"Point has coordinates: ({}, {}, {})",
mutable_borrow2.x, mutable_borrow2.y, mutable_borrow2.z
);
// TODO ^ Try uncommenting this line
// Immutable references go out of scope
}
{
let mutable_borrow = &mut point;
// Change data via mutable reference
mutable_borrow.x = 5;
mutable_borrow.y = 2;
mutable_borrow.z = 1;
// Error! Can't borrow `point` as immutable because it's currently
// borrowed as mutable.
//let y = &point.y;
// TODO ^ Try uncommenting this line
// Error! Can't print because `println!` takes an immutable reference.
//println!("Point Z coordinate is {}", point.z);
// TODO ^ Try uncommenting this line
// Ok! Mutable references can be passed as immutable to `println!`
println!(
"Point has coordinates: ({}, {}, {})",
mutable_borrow.x, mutable_borrow.y, mutable_borrow.z
);
// Mutable reference goes out of scope
}
// Immutable references to point are allowed again
let borrowed_point = &point;
println!(
"Point now has coordinates: ({}, {}, {})",
borrowed_point.x, borrowed_point.y, borrowed_point.z
);
}
最新的Rust编译器夜间版本(rustc 1.31.0-nightly (f99911a4a 2018-10-23)
)在Windows上运行此代码时不会出现编译错误。然而,在Rust Playground中,最新的Rust编译器夜间版本会提供预期的编译错误。
为什么会这样?为什么Rust编译器可以打破借用规则?如何在本地修复以获得预期的错误?