/
18_sort_by.go
62 lines (52 loc) · 1.47 KB
/
18_sort_by.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
// Seriál "Programovací jazyk Go"
// https://www.root.cz/serialy/programovaci-jazyk-go/
//
// Dvacátá čtvrtá část
// Kontejnery v základní knihovně programovacího jazyka Go
// https://www.root.cz/clanky/kontejnery-v-zakladni-knihovne-programovaciho-jazyka-go/
//
// Repositář:
// https://github.com/tisnik/go-root/
//
// Seznam demonstračních příkladů z dvacáté čtvrté části:
// https://github.com/tisnik/go-root/blob/master/article_24/README.md
//
// Demonstrační příklad číslo 18:
// Seřazení sekvence uživatelských datových struktur
package main
import (
"fmt"
"sort"
)
// Role represents user role in some IS
type Role struct {
name string
surname string
}
func printRoles(roles []Role) {
for i, role := range roles {
fmt.Printf("#%d: %s %s\n", i, role.name, role.surname)
}
}
func main() {
roles := []Role{
{"Eliška", "Najbrtová"},
{"Jenny", "Suk"},
{"Anička", "Šafářová"},
{"Sváťa", "Pulec"},
{"Blažej", "Motyčka"},
{"Eda", "Wasserfall"},
{"Přemysl", "Hájek"},
}
fmt.Println("Unsorted:")
printRoles(roles)
fmt.Println("--------------------")
sort.Slice(roles, func(i, j int) bool { return roles[i].name < roles[j].name })
fmt.Println("Sorted by name:")
printRoles(roles)
fmt.Println("--------------------")
sort.Slice(roles, func(i, j int) bool { return roles[i].surname < roles[j].surname })
fmt.Println("Sorted by surname:")
printRoles(roles)
fmt.Println("--------------------")
}