47. Vec::pop_if — Conditionally Pop the Last Element
Need to remove the last element of a Vec only when it meets a condition? Vec::pop_if does exactly that — no index juggling, no separate check-then-pop.
The old way
Before pop_if, you’d write something like this:
| |
Two separate calls, and a subtle TOCTOU gap if you’re not careful — last() checks one thing, then pop() acts on an assumption.
Enter pop_if
Stabilized in Rust 1.86, pop_if combines the check and the removal into one atomic operation:
| |
The closure receives a &mut T reference to the last element. If it returns true, the element is removed and returned as Some(T). If false (or the vec is empty), you get None.
Mutable access inside the predicate
Because the closure gets &mut T, you can even modify the element before deciding whether to pop it:
| |
A practical use: draining from the back
pop_if is handy for processing a sorted vec from the tail. Think of a priority queue backed by a sorted vec where you only want to process items above a threshold:
| |
Clean, expressive, and no off-by-one errors. Another small addition to Vec that makes everyday Rust just a bit nicer.