Sorting by functions
Context
Section titled “Context”For custom sorting (e.g., by struct field), use sort.Slice with a less function. This avoids implementing sort.Interface.
Example
Section titled “Example”Sort a slice of structs by age and by name.
Code example
Section titled “Code example”package main
import ( "fmt" "sort")
type Person struct { Name string Age int}
func main() { people := []Person{ {"Alice", 30}, {"Bob", 25}, {"Charlie", 35}, }
// Sort by Age (ascending) sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age }) fmt.Println("By age:", people)
// Sort by Name (descending) sort.Slice(people, func(i, j int) bool { return people[i].Name > people[j].Name }) fmt.Println("By name descending:", people)}Output
Section titled “Output”By age: [{Bob 25} {Alice 30} {Charlie 35}]By name descending: [{Charlie 35} {Bob 25} {Alice 30}]