Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4);
println!("{first}");
}It does not compile
- Expecting
1becausepushonly adds at the end: it may move every element to a new place, so the compiler refuses a live&v[0]across it (E0502). - Expecting the conflict to show up at run time: borrow rules are checked during the build, so this program never starts.
- How would you change one line so that the program compiles and prints
1? - Why is a live reference to an element a problem when
pushneeds more room?