Since the Rust book v1.30 says explicitly:
... constants in Rust have no fixed address in memory. This is because they’re effectively inlined to each place that they’re used. References to the same constant are not necessarily guaranteed to refer to the same memory address for this reason.
why the compiler allows getting a mutable reference on a const variable. It only says a warning/note and not an error.
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
To test this, a trivial code sample:
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
}
As expected, the memory location of the const may change (specially when accessed using a mutable reference).