77. repeat_n — Repeat a Value Exactly N Times
Stop writing repeat(x).take(n) — there’s a dedicated function that’s both cleaner and more efficient.
The old way
If you wanted an iterator that yields a value a fixed number of times, you’d chain repeat with take:
| |
This works fine for Copy types, but it always clones the value — even on the last iteration, where you could just move it instead.
Enter repeat_n
std::iter::repeat_n does exactly what the name says — repeats a value n times:
| |
Cleaner, more readable, and it comes with a hidden superpower.
The efficiency win
repeat_n moves the value on the last iteration instead of cloning it. This matters when cloning is expensive:
| |
With repeat(x).take(n), you’d clone all n times. With repeat_n, you save one clone. For large buffers or complex types, that’s a meaningful win.
repeat_n with zero
Passing n = 0 yields an empty iterator, and the value is simply dropped — no clones happen at all:
| |
When to reach for it
Use repeat_n whenever you need a fixed number of identical values. Common patterns:
| |
Small change, but it makes intent crystal clear: you want exactly n copies, no more, no less.