[Go] Sort a slice of strings alphabetically

Created on November 28, 2026

You can use sort.Slice to sort a slice of strings alphabetically. Go's comparison operators work with strings. This example sorts strArray in ascending alphabetical order.

package main

import (
    "fmt"
    "sort"
)

func main() {
    strArray := []string{"aab", "aac", "aaa", "aae", "aad"}
    sort.Slice(strArray, func(i, j int) bool {
        return strArray[i] < strArray[j]
    })
    fmt.Println(strArray)
}

The program produces the following output.

[aaa aab aac aad aae]
Go