由于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
}
->
{{链接1:Rust playground}}
正如预期的那样,const
的内存位置可能会发生变化(特别是在使用可变引用时访问时)。
&mut 1
这样的东西是完全允许的(有时非常有用!),那么没有理由不允许&mut FOO
,其中FOO
是1。但是可能会发现大多数&mut FOO
实际上都是错误的,这就是为什么引入了警告的原因。 - user4815162342