111
|
1 // Copyright 2011 The Go Authors. All rights reserved.
|
|
2 // Use of this source code is governed by a BSD-style
|
|
3 // license that can be found in the LICENSE file.
|
|
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 // ByAge implements sort.Interface for []Person based on
|
|
22 // the Age field.
|
|
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)
|
131
|
38 // There are two ways to sort a slice. First, one can define
|
|
39 // a set of methods for the slice type, as with ByAge, and
|
|
40 // call sort.Sort. In this first example we use that technique.
|
111
|
41 sort.Sort(ByAge(people))
|
|
42 fmt.Println(people)
|
|
43
|
131
|
44 // The other way is to use sort.Slice with a custom Less
|
|
45 // function, which can be provided as a closure. In this
|
|
46 // case no methods are needed. (And if they exist, they
|
|
47 // are ignored.) Here we re-sort in reverse order: compare
|
|
48 // the closure with ByAge.Less.
|
|
49 sort.Slice(people, func(i, j int) bool {
|
|
50 return people[i].Age > people[j].Age
|
|
51 })
|
|
52 fmt.Println(people)
|
|
53
|
111
|
54 // Output:
|
|
55 // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
|
|
56 // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
|
131
|
57 // [John: 42 Bob: 31 Jenny: 26 Michael: 17]
|
111
|
58 }
|