Rfcs: `pushed` for returning a mutable reference to the pushed element.

Created on 18 Dec 2016  Â·  8Comments  Â·  Source: rust-lang/rfcs

It is annoying to manually fetch the last element, which is unsurprisingly quite common after a push. The most obvious thing would be to make Vec::<T>::push() return a &mut T, but this is strictly speaking a breaking change. It would be cool to get some crater data on whether this in practice is an issue (i.e. if people don't put the ; after push() in functions returning ()).

The more realistic change is to add a method, push_ref, returning &mut T.

T-libs

Most helpful comment

IIRC, v.back() <- elem was supposed to produce a &mut T to the element.

All 8 comments

Hi @ticki,

Why not push_mut_ref according to conventions?

I'd really like this too, but bikeshed: I don't like the name push_ref; it sounds like you're pushing a reference. Maybe pushed_ref?

@KalitaAlexey Two reasons:

  1. The actual idiom is to use push_mut (like AsMut::as_mut).

  2. Using _mut makes no sense when there is no non-mutuable alternative.

@comex what about pushed()? It's simpler and nicer IMO.

@ticki Sure.

The emplacement implementation could be made to return the reference to an element that has been just emplaced. I wonder, though, which is more useful – returning the index of the element or the reference to the element itself.

@nagisa

Returning a reference allows working around the implicit boundcheck, and honestly, getting the index isn't that hard (it's free too).

IIRC, v.back() <- elem was supposed to produce a &mut T to the element.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Diggsey picture Diggsey  Â·  3Comments

onelson picture onelson  Â·  3Comments

mahkoh picture mahkoh  Â·  3Comments

steveklabnik picture steveklabnik  Â·  4Comments

camden-smallwood-zz picture camden-smallwood-zz  Â·  3Comments