Slices Rotate Shifts In Place

Rotate slice elements left in place with slices.Rotate: no new backing array, wraparound at the end, and composable repeated shifts.

GoData Integrity

Code

gosnippet
22 lines
package main

import (
	"fmt"
	"slices"
)

func main() {
	shifts := []string{"alice", "bob", "carol", "dave", "erin"}

	// Rotate 原地左移 shift n 位:不分配新底层数组,末尾回绕
	slices.Rotate(shifts, 2)
	fmt.Println("after +2:", shifts)

	// 再次旋转继续推进次序,n 取 0 等价于不变
	slices.Rotate(shifts, 1)
	fmt.Println("after +1:", shifts)

	// 配合取模可实现任意跳转:左移 len-1 等价于右移一位
	slices.Rotate(shifts, 4)
	fmt.Println("after +4:", shifts)
}

Inside the code

The moving parts are the function main.

Points of care

  • There is no install step — the platform ships all the APIs used.

Applying it

The main signature reads func main()

Look for the after +2:, after +1:, after +4: prefixes when the file runs; they tie each line to its step.

Statements that matter

shifts := []string{"alice", "bob", "carol", "dave", "erin"}

Interactive Tools for This Topic

FAQ

What does Slices Rotate Shifts In Place print when run?
No setup needed: run the file and look for labeled lines like `after +2:`, `after +1:`, `after +4:` in the output.