← 中文资源

简体中文版本

slices Rotate 原地左移切片

slices.Rotate 把切片元素原地左移 n 位:不分配新的底层数组,末尾自动回绕,连续旋转即可推进轮班、轮询的次序,n 取 0 等价于不变。

阅读英文原文

实现说明

slices Rotate 原地左移切片可以归结为函数 main。

使用要点

  • 跑完文件,输出里会留下标记——after +2:、after +1:、after +4:。

常见问题

运行「slices Rotate 原地左移切片」会打印什么?

整个文件跑完,输出行以 after +2:、after +1:、after +4: 这类前缀开头。

核心语句

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

代码示例

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)
}