70. Iterator::intersperse — Join Elements Without Collecting First
Tired of collecting into a Vec just to call .join(",")? intersperse inserts a separator between every pair of elements — lazily, right inside the iterator chain.
The problem
You have an iterator of strings and want to join them with a separator. The classic approach forces you to collect first:
| |
It gets the job done, but that intermediate Vec allocation is wasteful — you’re collecting just to immediately consume it again.
The clean way
intersperse inserts a separator value between every adjacent pair of elements, returning a new iterator:
| |
No intermediate Vec. The separator is lazily inserted as you iterate, and collect builds the final String directly.
It works with any type
intersperse isn’t just for strings — it works with any iterator where the element type implements Clone:
| |
This is handy for building sequences with delimiters, padding, or sentinel values between real data.
When the separator is expensive to create
If your separator is costly to clone, use intersperse_with — it takes a closure that produces the separator on demand:
| |
The closure is only called when a separator is actually needed, so you pay zero cost for single-element or empty iterators.
Edge cases
intersperse handles the corners gracefully — empty iterators stay empty, and single-element iterators pass through unchanged:
| |
Next time you reach for .collect::<Vec<_>>().join(...), try intersperse instead — it’s one less allocation and reads just as clearly.