Junior — Middle
How can you sort an array of structs in Go?
sobes.tech AI
Answer from AI
In Go, to sort an array of structs, you can use the sort package. You need to implement the sort.Interface, which requires three methods: Len(), Less(i, j int) bool, and Swap(i, j int).
Example of sorting a slice of structs by one of the fields:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
sort.Sort(ByAge(people))
fmt.Println(people)
}
As a result, the people slice will be sorted by age.