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?
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?
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.
Can invoke mut fn on const variable
Emphasis mine. If it's a variable, what's wrong with that?
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.
This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.