107. Vec::splice — Replace a Range and Keep the Old Values
Need to swap a chunk of a Vec for a different number of items? Most people reach for drain plus extend and a bunch of bookkeeping. Vec::splice does the whole thing in one call — and even hands back what it removed.
The clunky way
You want to replace v[1..4] with two different values. Without splice, you end up juggling indices:
| |
Three steps, one temporary Vec, and you didn’t even capture what was removed. Easy to off‑by‑one, easy to get wrong.
Enter splice
splice takes a range and an iterator and swaps them in place — the replacement can be any length:
| |
One call. No tail buffer. Works whether the replacement is shorter, longer, or the same size as the range.
It returns the removed items too
splice is a draining iterator — collect it and you get the elements that were taken out:
| |
Perfect for “swap this section, but undo it later” patterns.
Insert without removing
Pass an empty range and splice becomes a multi‑item insert:
| |
That’s far nicer than calling insert in a loop and watching every push shift the tail again.
When to reach for it
Any time you’d write drain(..) followed by extend(..) or a tower of insert calls, try splice first. One method, one allocation pattern, and the removed items come along for free.