How to Sort Strings Locale-Aware in Go with collate

Sort strings in Go using the collate package to respect locale-specific rules like accents and special characters.

Use golang.org/x/text/collate to sort strings according to locale rules instead of byte order. Create a collator for your target locale and pass it to sort.Slice with collator.Compare as the comparison function.

import (
	"sort"
	"golang.org/x/text/collate"
	"golang.org/x/text/language"
)

strings := []string{"apple", "banana", "Γ…ngstrΓΆm", "Zebra"}
c := collate.New(language.English)
sort.Slice(strings, func(i, j int) bool {
	return c.CompareString(strings[i], strings[j]) < 0
})