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


#1

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);

https://play.rust-lang.org/?gist=dfb0599c1e963a0317fd104daf9bc4dc&version=stable


#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.


#3

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.


#4

https://play.rust-lang.org/?gist=9d2a8069b51ea8a3ae789028400f57fa&version=stable


#5

Thanks. Misread his question :slight_smile:


#6

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