Junior — Middle
Wie kann man ein Array von Strukturen in der Programmiersprache Go sortieren?
sobes.tech KI
Antwort von AI
In Go kann man ein Array von Strukturen mit dem Paket sort sortieren. Dazu muss die Schnittstelle sort.Interface implementiert werden, die drei Methoden erfordert: Len(), Less(i, j int) bool und Swap(i, j int).
Beispiel für die Sortierung eines Slices von Strukturen nach einem ihrer Felder:
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)
}
Das Slice people wird nach Alter sortiert.