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

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?

6 Likes

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

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

7 Likes

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.

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

1 Like

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?

9 Likes

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

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

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

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.

1 Like

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.

2 Likes

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

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