How do I reverse a slice in go?

This will return a reversed slice without modifying the original slice.

Algorithm used from official wiki page: https://github.com/golang/go/wiki/SliceTricks#reversing

func reverse(s []interface{}) []interface{} {
    a := make([]interface{}, len(s))
    copy(a, s)

    for i := len(a)/2 - 1; i >= 0; i-- {
        opp := len(a) - 1 - i
        a[i], a[opp] = a[opp], a[i]
    }

    return a
}

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

Run the code on the Go playground.

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.

Tags:

Go