[Idea] Return a reference to the element which were just pushed onto a Vec


#1

I often push an element to a Vec and then call last().unwrap() to get a reference to it. Is there a reason why push should not return the reference to the pushed element?


#2

This seems like something you could use a trait to solve. Besides, what kind of reference would push return? & or &mut?


#3

As push needs a &mut self anyway, it should return &mut.


#4

We can’t change the type of such a commonly used pre-existing method for compatibility reasons. There should definitely be a new method for this though.


#5

This feels a bit odd. Since you are pushing an item to the vec, you already have the item with you. So having push return a item feels redundant


#6

The item will often be owned by the container you’re pushing into, so now you no longer have it. I, too, have definitely encountered the case where I wanted to push something into a container and get back a reference.

Maybe we need something akin to HashMap::entry() for Vec?


#7

Ah true. Yeah the entry API would make sense and keep things consistent with other collections.


#8

I’ve definitely wanted this for HashMaps – at least with Vec it’s cheap to get a reference to what I just inserted.


#9

For maps we already have the entry API, which should solve this problem (HashMap::entry)


#10

I don’t know that we need a full entry API, since this doesn’t need to look up existing items – although that could be a thing too. Here I would suggest:

fn push_last(&mut self, value: T) -> &mut T

Maybe insert deserves a variant too, but I don’t have a name suggestion.


#11

I think insert is the corresponded entry.

One advantage of a full entry API would be, that you could also return the index of the last element, no need to another call to len.


#12

Not for the key, though, which is also moved.


closed #13

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.