![](/img/trans.png)
[英]Why is casting a const reference directly to a mutable reference invalid in Rust?
[英]Why mutable reference on `const` is not an error?
由于Rust 书 v1.30明确表示:
... Rust 中的常量在 memory中没有固定地址。 这是因为它们有效地内联到使用它们的每个地方。 因此,对相同常量的引用不一定保证引用相同的 memory 地址。
为什么编译器允许获取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
的 memory 位置可能会改变(特别是在使用可变引用访问时)。
在某些情况下,它的行为是可预测的。 特别是,如果您重复使用相同的参考:
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;
}
与首先添加本地绑定相比,我无法立即想到这样做是有益的。 但它不会导致 memory 不安全,因此不必担心。
鉴于这在 Rust 版本 1.0 中不是错误,Rust 开发人员以后不能让它成为错误,因为这会破坏向后兼容性。
对常量进行可变引用会创建一个新的临时变量。 您的代码被编译器视为:
fn main() {
const VALUE : u64 = 0;
println!("{:p}", &VALUE); // 0x10622ed78 // same
println!("{:p}", &VALUE); // 0x10622ed78
let mut tmp1 = VALUE;
println!("{:p}", &mut tmp1); // 0x7ffee9a08890 // different
let mut tmp2 = VALUE;
println!("{:p}", &mut tmp2); // 0x7ffee9a088e8
}
这似乎是一种奇怪的做事方式,当常量是function 指针或具有内部可变性时,这种行为有合法的用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.