liyujie
2025-08-28 d9927380ed7c8366f762049be9f3fee225860833
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
 
package sort_test
 
import (
   "fmt"
   "sort"
)
 
type Grams int
 
func (g Grams) String() string { return fmt.Sprintf("%dg", int(g)) }
 
type Organ struct {
   Name   string
   Weight Grams
}
 
type Organs []*Organ
 
func (s Organs) Len() int      { return len(s) }
func (s Organs) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
 
// ByName implements sort.Interface by providing Less and using the Len and
// Swap methods of the embedded Organs value.
type ByName struct{ Organs }
 
func (s ByName) Less(i, j int) bool { return s.Organs[i].Name < s.Organs[j].Name }
 
// ByWeight implements sort.Interface by providing Less and using the Len and
// Swap methods of the embedded Organs value.
type ByWeight struct{ Organs }
 
func (s ByWeight) Less(i, j int) bool { return s.Organs[i].Weight < s.Organs[j].Weight }
 
func Example_sortWrapper() {
   s := []*Organ{
       {"brain", 1340},
       {"heart", 290},
       {"liver", 1494},
       {"pancreas", 131},
       {"prostate", 62},
       {"spleen", 162},
   }
 
   sort.Sort(ByWeight{s})
   fmt.Println("Organs by weight:")
   printOrgans(s)
 
   sort.Sort(ByName{s})
   fmt.Println("Organs by name:")
   printOrgans(s)
 
   // Output:
   // Organs by weight:
   // prostate (62g)
   // pancreas (131g)
   // spleen   (162g)
   // heart    (290g)
   // brain    (1340g)
   // liver    (1494g)
   // Organs by name:
   // brain    (1340g)
   // heart    (290g)
   // liver    (1494g)
   // pancreas (131g)
   // prostate (62g)
   // spleen   (162g)
}
 
func printOrgans(s []*Organ) {
   for _, o := range s {
       fmt.Printf("%-8s (%v)\n", o.Name, o.Weight)
   }
}