Source file
src/sort/example_wrapper_test.go
1
2
3
4
5 package sort_test
6
7 import (
8 "fmt"
9 "sort"
10 )
11
12 type Grams int
13
14 func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
15
16 type Organ struct {
17 Name string
18 Weight Grams
19 }
20
21 type Organs []*Organ
22
23 func (s Organs) Len() int { return len(s) }
24 func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
25
26
27
28 type ByName struct{ Organs }
29
30 func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
31
32
33
34 type ByWeight struct{ Organs }
35
36 func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
37
38 func Example_sortWrapper() {
39 s := []*Organ{
40 {"brain", 1340},
41 {"heart", 290},
42 {"liver", 1494},
43 {"pancreas", 131},
44 {"prostate", 62},
45 {"spleen", 162},
46 }
47
48 sort.Sort(ByWeight{s})
49 fmt.Println("Organs by weight:")
50 printOrgans(s)
51
52 sort.Sort(ByName{s})
53 fmt.Println("Organs by name:")
54 printOrgans(s)
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71 }
72
73 func printOrgans(s []*Organ) {
74 for _, o := range s {
75 fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
76 }
77 }
78
View as plain text