/
5exercise.go
95 lines (76 loc) · 1.91 KB
/
5exercise.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package main
import (
"fmt"
"sort"
)
type user struct {
First string
Last string
Age int
Sayings []string
}
type ByAge []user
func (bA ByAge) Len() int { return len(bA) }
func (bA ByAge) Less(i, j int) bool { return bA[i].Age < bA[j].Age }
func (bA ByAge) Swap(i, j int) { bA[i], bA[j] = bA[j], bA[i] }
type ByLast []user
func (bL ByLast) Len() int { return len(bL) }
func (bL ByLast) Less(i, j int) bool { return bL[i].Last < bL[j].Last }
func (bL ByLast) Swap(i, j int) { bL[i], bL[j] = bL[j], bL[i] }
func main() {
u1 := user{
First: "James",
Last: "Bond",
Age: 32,
Sayings: []string{
"Shaken, not stirred",
"Youth is no guarantee of innovation",
"In his majesty's royal service",
},
}
u2 := user{
First: "Miss",
Last: "Moneypenny",
Age: 27,
Sayings: []string{
"James, it is soo good to see you",
"Would you like me to take care of that for you, James?",
"I would really prefer to be a secret agent myself.",
},
}
u3 := user{
First: "M",
Last: "Hmmmm",
Age: 54,
Sayings: []string{
"Oh, James. You didn't.",
"Dear God, what has James done now?",
"Can someone please tell me where James Bond is?",
},
}
users := []user{u1, u2, u3}
fmt.Println("\nRaw below:")
for _, usr := range users {
fmt.Println("User:\t", usr.First, usr.Last, usr.Age)
sort.Strings(usr.Sayings)
for _, saying := range usr.Sayings {
fmt.Println("Sayings: ", saying)
}
}
sort.Stable(ByAge(users))
fmt.Println("\nSort by Age below:")
for _, usr := range users {
fmt.Println("User:\t", usr.First, usr.Last, usr.Age)
for _, saying := range usr.Sayings {
fmt.Println("Sayings: ", saying)
}
}
sort.Stable(ByLast(users))
fmt.Println("\nSort by Last below:")
for _, usr := range users {
fmt.Println("User:\t", usr.First, usr.Last, usr.Age)
for _, saying := range usr.Sayings {
fmt.Println("Sayings: ", saying)
}
}
}