为什么对`const`的可变引用不是错误?
由于Rust book v1.30明确指出:
... Rust 中的常量在内存中没有固定地址。这是因为它们有效地内联到每个使用它们的地方。由于这个原因,对相同常量的引用不一定保证引用相同的内存地址。
为什么编译器允许得到一个可变的引用上一个const变量。它只是说一个警告/注意事项,而不是一个错误。
warning: taking a mutable reference to a `const` item
--> src/main.rs:5:22
|
6 | println!("{:p}", &mut VALUE);
| ^^^^^^^^^^
|
= note: `#[warn(const_item_mutation)]` on by default
= note: each usage of a `const` item creates a new temporary
= note: the mutable reference will refer to this temporary, not the original `const` item
为了测试这一点,一个简单的代码示例:
fn main() {
const VALUE: u64 = 0;
println!("{:p}", &VALUE); // 0x10622ed78 // same
println!("{:p}", &VALUE); // 0x10622ed78
println!("{:p}", &mut VALUE); // 0x7ffee9a08890 // different
println!("{:p}", &mut VALUE); // 0x7ffee9a088e8
}
铁锈游乐场
正如预期的那样, 的内存位置const可能会改变(特别是在使用可变引用访问时)。
回答
在某些情况下,它的行为是可预测的。特别是,如果您重复使用相同的引用:
const VALUE: u64 = 0;
fn main() {
let v = &mut VALUE;
add_1(v);
add_1(v);
assert_eq!(*v, 2);
}
fn add_1(v: &mut u64) {
*v += 1;
}
与首先添加本地绑定相比,我无法立即想到这样做是有益的。但它不会导致内存不安全,所以这不是一个很大的担忧。
鉴于这不是 Rust 1.0 版中的错误,Rust 开发人员以后不能让它成为错误,因为这会破坏向后兼容性。