-
Notifications
You must be signed in to change notification settings - Fork 0
/
sorting03.go
63 lines (50 loc) · 1.31 KB
/
sorting03.go
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
/* Alta3 Research | RZFeeser
Custom Sorting - Sorting structs with custom functions */
package main
import (
"fmt"
"sort"
)
// record a "Person" Name, Age
type Person struct {
Name string
Age int
}
/* In Go, if you define "String()" for a struct
the result is a custom "ToString". That is to say,
we can control the "view" that is returned when someone tries
to print our struct */
func (p Person) String() string {
return fmt.Sprintf("%s: %d", p.Name, p.Age)
}
// ByAge implements sort.Interface for []Person based on
// the Age field
type ByAge []Person
func (a ByAge) Len() int {
return len(a)
}
func (a ByAge) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a ByAge) Less(i, j int) bool {
return a[i].Age < a[j].Age
}
func main() {
// Name, Age
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
/* If you commented out the "String()" function,
the way the people struct is displayed will change.
The formatting it is following is provided by the "String()"
function */
fmt.Println(people)
// We defined the interface for sort.Sort
// a set of methods for the slice type, as with ByAge, and
// call sort.Sort.
sort.Sort(ByAge(people))
fmt.Println(people)
}