How do I reverse an array in Go?

Honestly this one is simple enough that I’d just write it out like this:

package main

import "fmt"

func main() {

    s := []int{5, 2, 6, 3, 1, 4}

    for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
        s[i], s[j] = s[j], s[i]
    }

    fmt.Println(s)
}

http://play.golang.org/p/vkJg_D1yUb

(The other answers do a good job of explaining sort.Interface and how to use it; so I won’t repeat that.)

Leave a Comment