0 Tage Serie
go / intermediate
Snippet

Sortieren von Struct-Slices mithilfe des sort.Interface-Vertrags

Um eine benutzerdefinierte Collection in Go mit dem Standard-Paket sort zu sortieren, implementieren Sie das sort.Interface-Interface. Dieses Interface erfordert drei Methoden: Len(), Swap(i, j int) und Less(i, j int) bool. Sobald diese Methoden für einen Typ definiert sind, sortiert der Aufruf von sort.Sort() die Elemente effizient an Ort und Stelle.

snippet.go
go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
package main
import (
"fmt"
"sort"
)
type Product struct {
Name string
Price float64
}
type ByPrice []Product
func (a ByPrice) Len() int { return len(a) }
func (a ByPrice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }
func main() {
products := ByPrice{
{"Laptop", 999.99},
{"Mouse", 19.99},
{"Keyboard", 49.99},
}
sort.Sort(products)
for _, p := range products {
fmt.Printf("%s: $%.2f\n", p.Name, p.Price)
}
}
Erklärung
1
type ByPrice []Product
Definiert einen benutzerdefinierten Slice-Typ von Product, auf dem die Sortiermethoden definiert werden.
2
func (a ByPrice) Len() int { return len(a) }
Gibt die Anzahl der Elemente im Slice zurück und erfüllt den ersten Teil von sort.Interface.
3
func (a ByPrice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
Vertauscht Elemente an den Indizes i und j, was für In-Place-Sortieralgorithmen erforderlich ist.
4
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }
Definiert das Sortierkriterium und gibt true zurück, wenn Element i vor Element j stehen soll.
5
sort.Sort(products)
Ruft den Sortieralgorithmus des sort-Pakets auf, um den Slice an Ort und Stelle zu sortieren.