Rotate Slices In Place With rotate_left
Rotate a slice in place with rotate_left and rotate_right, a cheap way to move a buffered window without allocating or copying manually.
Code
fn main() {
let mut buffer = [1, 2, 3, 4, 5];
// Rotate slices in place without allocating
buffer.rotate_left(2); // 前两个元素移到尾部
println!("after rotate_left: {:?}", buffer);
let mut window = [1, 2, 3, 4, 5];
window.rotate_right(1); // 最后一个元素移到头部
println!("after rotate_right: {:?}", window);
// 环形缓冲:消费到某个位置后,把下一个可读位置转到起点
let mut ring = [10, 20, 30, 40, 50, 60];
let consumed = 2;
ring.rotate_left(consumed);
println!("ring read order: {:?}", ring);
// 旋转量先对长度取模,避免越界 panic
let mut values = [1, 2, 3];
let shift = 7 % values.len();
values.rotate_left(shift);
println!("mod rotation: {:?}", values);
}How it works
Rotate Slices In Place With rotate_left keeps everything in the function main.
Applying it
The demo output is labeled (after rotate_left:, after rotate_right:, ring read order:), so every printed line maps back to its originating operation.
Statements that matter
let mut ring = [10, 20, 30, 40, 50, 60];
window.rotate_right(1); // 最后一个元素移到头部
println!("after rotate_right: {:?}", window);
buffer.rotate_left(2); // 前两个元素移到尾部
println!("after rotate_left: {:?}", buffer);
Interactive Tools for This Topic
FAQ
- What does Rotate Slices In Place With rotate_left print when run?
- Running the file directly is enough — expect labeled output lines such as `after rotate_left:`, `after rotate_right:`, `ring read order:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.