As per rust book (vectors section - Ch-8.1)
let mut v = vec![1, 2, 3, 4, 5];
let first = &v[0]; // <-- This is an immutable borrow
v.push(6); // Which is why push() operation is not allowed (since this is a mutable borrow)
println!("The first element is: {}", first);
Because &v[0] is an immutable borrow, v.push(100) operation should not work. Which makes sense.
However, this works:
let mut v = vec![1, 2, 3, 4, 5];
let first = v[0];
v.push(6);
println!("The first element is: {}", first);
When & is removed from v[0], push() operation works fine.
Question(s):
- If adding
&creates a reference (and does not move ownership), does this mean after removing&, the ownership ofv[0]is moved to variablefirst? If so, I am able to accessv[0]afterwards. Why is that? - If (1) is not the case, is this a
Copyoperation? i.e value stored at memory locationv[0]is copied to variablefirst? - If not (2), what exactly is happening here?