标准库没有用于反转切片的内置函数.使用for循环反转切片:
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
在GO 1.18或更高版本中使用类型参数编写通用反转函数:
func reverse[S ~[]E, E any](s S) {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
}
使用reflect.Swapper在GO 1.8版或更高版本中编写处理任意切片类型的函数:
func reverse(s interface{}) {
n := reflect.ValueOf(s).Len()
swap := reflect.Swapper(s)
for i, j := 0, n-1; i < j; i, j = i+1, j-1 {
swap(i, j)
}
}
Run the code on the Go playground美元.
此答案中的函数将切片反转到位.如果不想修改原始切片,请在反转切片之前执行copy the slice.