Sort Slice of Numbers in Golang

Create new folder named src. In src folder, create new file named main.go as below:

package main

import (
	"fmt"
	"sort"
)

func main() {

	fmt.Println("Sort ASC")
	slice1 := []int{4, 1, -2, 9, 10}
	sort.Ints(slice1)
	fmt.Println(slice1)

	fmt.Println("Sort DESC")
	slice2 := []int{4, 1, -2, 9, 10}
	sort.Slice(slice2, func(i, j int) bool {
		return slice2[i] >= slice2[j]
	})
	fmt.Println(slice2)

}




Open Terminal windows in Visual Studio Code and run command line: go run main.go

Sort ASC
[-2 1 4 9 10]

Sort DESC
[10 9 4 1 -2]