133. slice::rotate_left — Cycle Elements Through a Slice Without a Second Buffer
Need the first few elements to wrap around to the back? slice.rotate_left(n) cycles them through in place — no scratch Vec, no clever indexing, no borrow checker drama.
The Problem
Rotating a slice “the obvious way” means allocating a temporary, copying things twice, and being very careful about ranges:
| |
It works, but it allocates and only runs on Vec. The moment you only have a &mut [T] — a window inside a larger buffer, say — to_vec/drain aren’t options at all.
After: rotate_left and rotate_right
Every slice already knows how to rotate itself in place:
| |
rotate_left(n) moves the first n elements to the end; rotate_right(n) moves the last n to the front. Both run in O(len) with zero allocations, and they work on any &mut [T] — arrays, vector slices, sub-ranges of bigger buffers.
Where It Earns Its Keep
Round-robin scheduling: the first runner takes a turn, then moves to the back of the line.
| |
Scrolling a fixed-size display buffer — drop the oldest row, leave a slot at the end for the newest:
| |
And because it operates on &mut [T], you can rotate a window inside a larger buffer without splitting it:
| |
Anywhere you’d reach for “shift everything left and stick the front on the end,” rotate_left does it in one line with no allocation.