Why do I get no warning (assigning to const array)?

I accidentally declared a local array const instead of let mut and the compiler just compiled it. Instead of changing a value later on, it just does nothing. This is not something I would expect:

fn main() {
    const tmp: [u8; 4] = [0; 4];
    tmp[0] = 3; 
    for v in &tmp {
        print!("{:02x} ", v);

The output is:

00 00 00 00

Instead of:

03 00 00 00

const values are copied into the code at the locations they are referenced. So you're mutating a temporary value. There's no warning for this because it is a perfectly useful thing to do (say, when you want to create a copy of a const value and modify it before storing it somewhere.)


If you want a true global, you would have to use static, but they can't be mutated safely without the use of techniques such as atomics or mutexes.

1 Like

A warning for cases where the mutated temporary is never read would be useful, though.


Yes, it would be nice if the line tmp[0] = 3; issued a warning that the temporary being assigned to was never used after the assignment. I'm not sure it would totally clarify things though, because then people would just be asking why the compiler says the value is never used even though they explicitly tried using it on the next line (unaware that this is a new temporary.)


That warning would still be useful, and could mention that const acts in an interesting way.


Array size is const

This is https://github.com/rust-lang/rust/issues/55721


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.