Can invoke mut fn on const variable; looks like bug

Code:

fn main() {
    const V: Vec<u32> = Vec::new();
    V.push(10);
    println!("{:?}", V); // prints []
}

I expect this to fail. But it works: play.

This is a bug, right?

It is going to be linted with https://github.com/rust-lang/rust/pull/75573 .

2 Likes

I wouldn't say it's a bug, more an artefact of how referring to a const is like copy-pasting the definition into that position.

It's no different to writing Vec::new().push(10)... A useless statement to be sure, but not incorrect.

2 Likes

Can invoke mut fn on const variable

Emphasis mine. If it's a variable, what's wrong with that? :wink:

TL;DR: a const is like a numeric or string literal in this regard – it gets reinstantiated/"copied" each time it's accessed, so V.push(10) actually pushes to a temporary empty vector.