How to reverse a slice in Go
Created
Modified
Using a for Loop
The standard library does not have a built-in function for reversing a slice. Use a for loop to reverse a slice:
package main
import "fmt"
func main() {
s := []string{"b", "c", "d"}
for i := len(s)/2 - 1; i >= 0; i-- {
s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
}
fmt.Printf("%q\n", s)
}
["d" "c" "b"]
The same thing, except with two indices:
package main
import "fmt"
func main() {
s := []string{"b", "c", "d"}
for l, r := 0, len(s)-1; l < r; l, r = l+1, r-1 {
s[l], s[r] = s[r], s[l]
}
fmt.Printf("%q\n", s)
}
["d" "c" "b"]
Using reflect.Swapper Function
Use reflect.Swapper to write a function that works with arbitrary slice types in Go version 1.8 or later:
package main
import (
"fmt"
"reflect"
)
func main() {
s := []string{"b", "c", "d"}
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)
}
fmt.Printf("%q\n", s)
}
["d" "c" "b"]
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.
Using Type Parameters
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]
}
}