go / intermediate
Snippet
Sorting Struct Slices Using the sort.Interface Contract
To sort a custom collection in Go using the standard sort package, you implement the sort.Interface interface. This interface requires three methods: Len(), Swap(i, j int), and Less(i, j int) bool. Once these methods are defined on a type, calling sort.Sort() will order the elements in-place efficiently.
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 mainimport ("fmt""sort")type Product struct {Name stringPrice float64}type ByPrice []Productfunc (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)}}
Breakdown
1
type ByPrice []Product
Defines a custom slice type of Product on which the sorting methods will be attached.
2
func (a ByPrice) Len() int { return len(a) }
Returns the number of elements in the slice, satisfying the first part of sort.Interface.
3
func (a ByPrice) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
Swaps elements at indices i and j, which is required for in-place sorting algorithms.
4
func (a ByPrice) Less(i, j int) bool { return a[i].Price < a[j].Price }
Defines the sorting criteria, returning true if element i should precede element j.
5
sort.Sort(products)
Invokes the quicksort/pdqsort algorithm provided by the sort package to sort the slice.