I was reading chapter Storing Lists of Values with Vectors . I was trying the example Attempting to add an element to a vector while holding a reference to an item
.
let mut _v: Vec<i32> = vec![2, 4, 6];
let _first = &_v[0];
_v.push(8);
println!("{:?}", _first);
It didn't compile, as per expected behavior. According to the book:-
When the program has a valid reference, the borrow checker enforces the ownership and borrowing rules (covered in Chapter 4) to ensure this reference and any other references to the contents of the vector remain valid. Recall the rule that states you can’t have mutable and immutable references in the same scope. That rule applies in Listing 8-7, where we hold an immutable reference to the first element in a vector and try to add an element to the end, which won’t work.
But if I remove last println
statement, the above code will compile. I am not able to understand how println!
macro affect above statement.
Please let me know if I am missing anything.