228. Vec::push_mut — Push and Get a &mut Back, Skip the last_mut().unwrap()
Pushed an element and immediately needed to tweak it? The old way was push then last_mut().unwrap(). Rust 1.95 added push_mut, which hands you the &mut right back.
The push-then-refetch dance
You add an element to a Vec, then need a mutable handle to it — to set a field, run a builder step, whatever. push returns (), so you go fishing for what you just put in:
| |
That last_mut().unwrap() is pure ceremony. You know it’s there — you pushed it one line ago — but the type system makes you unwrap an Option anyway.
push_mut returns the reference directly
Stabilized in Rust 1.95, Vec::push_mut appends the value and returns a &mut T to it in one step:
| |
No Option, no unwrap, no second lookup. The borrow checker is happy because the returned reference is tied to the Vec.
Where it shines: build-then-mutate loops
Parsing or accumulating state where each new entry gets refined before you move on reads much cleaner:
| |
Not just Vec
The same _mut family landed across the collections: Vec::insert_mut, VecDeque::push_front_mut / push_back_mut / insert_mut, and LinkedList::push_front_mut / push_back_mut all return a &mut to the freshly inserted element:
| |
Whenever you push and immediately need to touch what you pushed, reach for push_mut — the reference is already in your hand.