Sort Slice of Strings in Golang

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

package main

import (
	"fmt"
	"sort"
	"strings"
)

func main() {

	fmt.Println("Sort ASC")
	names1 := []string{"mary", "peter", "kevin", "anna", "johny"}
	sort.Strings(names1)
	fmt.Println(names1)

	fmt.Println("Sort DESC")
	names2 := []string{"mary", "peter", "kevin", "anna", "johny"}
	sort.Slice(names2, func(i, j int) bool {
		return strings.Compare(names2[i], names2[j]) > 0
	})
	fmt.Println(names2)

}




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

Sort ASC
[anna  johny  kevin  mary  peter]

Sort DESC
[peter  mary  kevin  johny  anna]