43. Vec::extract_if — Remove Elements and Keep Them
Ever needed to split a Vec into two groups — the ones you keep and the ones you remove? retain discards the removed items. Now there’s a better way.
Vec::extract_if (stable since Rust 1.87) removes elements matching a predicate and hands them back as an iterator — in a single pass.
The old way — two passes, logic must stay in sync
| |
The filter and the retain predicates must be inverses of each other — easy to mistype, and you touch the data twice.
The new way — one pass, one predicate
| |
extract_if walks the Vec, removes every element where the closure returns true, and yields it. The .. is a range — you can narrow it to only consider a slice of the vector.
Real-world example: draining a work queue
| |
HashMap and HashSet also gained extract_if in Rust 1.88.
Note: The closure takes
&mut T, so you can even mutate elements mid-extraction before deciding whether to remove them.