OLD | NEW |
1 // Copyright 2013 The Go Authors. All rights reserved. | 1 // Copyright 2013 The Go Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style | 2 // Use of this source code is governed by a BSD-style |
3 // license that can be found in the LICENSE file. | 3 // license that can be found in the LICENSE file. |
4 | 4 |
5 package sort_test | 5 package sort_test |
6 | 6 |
7 import ( | 7 import ( |
8 "fmt" | 8 "fmt" |
9 "sort" | 9 "sort" |
10 ) | 10 ) |
11 | 11 |
12 // A couple of type definitions to make the units clear. | 12 // A couple of type definitions to make the units clear. |
13 type solarMass float64 | 13 type earthMass float64 |
14 type au float64 | 14 type au float64 |
15 | 15 |
16 // A Planet defines the properties of a solar system object. | 16 // A Planet defines the properties of a solar system object. |
17 type Planet struct { | 17 type Planet struct { |
18 name string | 18 name string |
19 » mass solarMass | 19 » mass earthMass |
20 distance au | 20 distance au |
21 } | 21 } |
22 | 22 |
23 // By is the type of a "less" function that defines the ordering of its Planet a
rguments. | 23 // By is the type of a "less" function that defines the ordering of its Planet a
rguments. |
24 type By func(p1, p2 *Planet) bool | 24 type By func(p1, p2 *Planet) bool |
25 | 25 |
26 // Sort is a method on the function type, By, that sorts the argument slice acco
rding to the function. | 26 // Sort is a method on the function type, By, that sorts the argument slice acco
rding to the function. |
27 func (by By) Sort(planets []Planet) { | 27 func (by By) Sort(planets []Planet) { |
28 ps := &planetSorter{ | 28 ps := &planetSorter{ |
29 planets: planets, | 29 planets: planets, |
(...skipping 57 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
87 fmt.Println("By distance:", planets) | 87 fmt.Println("By distance:", planets) |
88 | 88 |
89 By(decreasingDistance).Sort(planets) | 89 By(decreasingDistance).Sort(planets) |
90 fmt.Println("By decreasing distance:", planets) | 90 fmt.Println("By decreasing distance:", planets) |
91 | 91 |
92 // Output: By name: [{Earth 1 1} {Mars 0.107 1.5} {Mercury 0.055 0.4} {V
enus 0.815 0.7}] | 92 // Output: By name: [{Earth 1 1} {Mars 0.107 1.5} {Mercury 0.055 0.4} {V
enus 0.815 0.7}] |
93 // By mass: [{Mercury 0.055 0.4} {Mars 0.107 1.5} {Venus 0.815 0.7} {Ear
th 1 1}] | 93 // By mass: [{Mercury 0.055 0.4} {Mars 0.107 1.5} {Venus 0.815 0.7} {Ear
th 1 1}] |
94 // By distance: [{Mercury 0.055 0.4} {Venus 0.815 0.7} {Earth 1 1} {Mars
0.107 1.5}] | 94 // By distance: [{Mercury 0.055 0.4} {Venus 0.815 0.7} {Earth 1 1} {Mars
0.107 1.5}] |
95 // By decreasing distance: [{Mars 0.107 1.5} {Earth 1 1} {Venus 0.815 0.
7} {Mercury 0.055 0.4}] | 95 // By decreasing distance: [{Mars 0.107 1.5} {Earth 1 1} {Venus 0.815 0.
7} {Mercury 0.055 0.4}] |
96 } | 96 } |
OLD | NEW |