How do I reverse a slice in go?

Issue

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?

Solution

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.

Answered By – Bayta Darell

Answer Checked By – Timothy Miller (GoLangFix Admin)

Leave a Reply

Your email address will not be published.