How do I reverse an arbitrary slice ([]interface{}
) in Go? I'd rather not have to write Less
and Swap
to use sort.Reverse
. Is there a simple, builtin way to do this?
Use slices.Reverse in Go 1.21 or later:
slices.Reverse(s)
Answers for Go version 1.20 and earlier:
The standard library does not have a built-in function for reversing a slice. Use a for loop to reverse a slice:
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
s[i], s[j] = s[j], s[i]
}
Use type parameters to write a generic reverse function in Go 1.18 or later:
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]
}
}
Use reflect.Swapper to write a function that works with arbitrary slice types in Go version 1.8 or later:
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)
}
}
The functions in this answer reverse the slice inplace. If you do not want to modify the original slice, copy the slice before reversing the slice.