Source file
src/sort/example_interface_test.go
1
2
3
4
5 package sort_test
6
7 import (
8 "fmt"
9 "sort"
10 )
11
12 type Person struct {
13 Name string
14 Age int
15 }
16
17 func (p Person) String() string {
18 return fmt.Sprintf("%s: %d", p.Name, p.Age)
19 }
20
21
22
23 type ByAge []Person
24
25 func (a ByAge) Len() int { return len(a) }
26 func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
27 func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
28
29 func Example() {
30 people := []Person{
31 {"Bob", 31},
32 {"John", 42},
33 {"Michael", 17},
34 {"Jenny", 26},
35 }
36
37 fmt.Println(people)
38
39
40
41 sort.Sort(ByAge(people))
42 fmt.Println(people)
43
44
45
46
47
48
49 sort.Slice(people, func(i, j int) bool {
50 return people[i].Age > people[j].Age
51 })
52 fmt.Println(people)
53
54
55
56
57
58 }
59
View as plain text