NOOB: Vec.last() and Vec.push()

How can I fetch the last item of a vector and then add a new one to it?

let v: Vec<usize> = vec![];
let last = v.last();
v.push(2);

If you want to push an element at the end of a vector you can use place_back() which is an experimental feature in the nightly build.

v.last() returns a reference into the vector - because you have a shared reference to something in the vector, you cannot mutate the vector (such as by pushing more items on the end of it).

You need to take the reference you got out of the vector and clone it, so you have full ownership of the thing you got from the vector. You can do that with the cloned() method. Then, you won't have any references into the vector, so you're free to mutate it again.

let mut v: Vec<usize> = vec![];
let last = v.last().cloned();
v.push(2);

@dylan.dpc place_back() is not helpful here. It does the same thing as push, the performance is just different in some cases.

5 Likes
1 Like

Thanks. Misread his question :slight_smile:

Thank you guys! I have to admit, that my question was described very bad.
Nevertheless, @withoutboats managed to answer it! Thank you

2 Likes