Sorting slices
The sorting of data is a very common task. The Go standard library simplifies the sorting by the sort package. This recipe gives a brief look at how to use it.
How to do it...
- Open the console and create the folder
chapter11/recipe07. - Navigate to the directory.
- Create the file
sort.gowith the following content:
package main
import (
"fmt"
"sort"
)
type Gopher struct {
Name string
Age int
}
var data = []Gopher{
{"Daniel", 25},
{"Tom", 19},
{"Murthy", 33},
}
type Gophers []Gopher
func (g Gophers) Len() int {
return len(g)
}
func (g Gophers) Less(i, j int) bool {
return g[i].Age > g[j].Age
}
func (g Gophers) Swap(i, j int) {
tmp := g[j]
g[j] = g[i]
g[i] = tmp
}
func main() {
sort.Slice(data, func(i, j int) bool {
...