/
mapdemo.go
66 lines (49 loc) · 1.52 KB
/
mapdemo.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
// An example of building a map having keys representing nations, and values representing
// the respective nation's capital.
package main
import (
"fmt"
"sort"
)
// An example of sorting the keys in a map alphabetically
func printSortedNationCapitalsMap(capitalsMap map[string]string) {
keys := make([]string, len(capitalsMap))
for key, _ := range capitalsMap {
keys = append(keys, key)
}
sort.Strings(keys)
for _, v := range keys {
if v == "" {
continue
}
fmt.Println("The capital of", v, "is ", capitalsMap[v])
}
}
func printNationCapitalsMap(capitalsMap map[string]string) {
for key, value := range capitalsMap {
fmt.Println("The capital of", key, "is ", value)
}
}
func nationCapitalsExample() {
// Note: In Go, maps have no contract to maintain the order of the keys
var nationCapitals map[string]string = make(map[string]string)
nationCapitals["Afghanistan"] = "Kabul"
nationCapitals["Canada"] = "Ottawa"
nationCapitals["Japan"] = "Tokyo"
nationCapitals["Kenya"] = "Nairobi"
nationCapitals["India"] = "New Delhi"
nationCapitals["Mexico"] = "Mexico City"
nationCapitals["South Korea"] = "Seoul"
nationCapitals["United Kingdom"] = "London"
nationCapitals["USA"] = "Washington D.C."
nationCapitals["Taiwan"] = "Taipei"
fmt.Println("Print the map unsorted (random order): ")
printNationCapitalsMap(nationCapitals)
fmt.Println("\n")
fmt.Println("Print the map sorted by key (nation name):")
printSortedNationCapitalsMap(nationCapitals)
fmt.Println("\n")
}
func main() {
nationCapitalsExample()
}