-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathmain.go
71 lines (53 loc) · 1.43 KB
/
main.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
package main
import "fmt"
type State struct {
name string
abbreviation string
population int
}
func main() {
fmt.Println("\n--- Map ---")
// Map isn't initialized and is nil.
var states map[string]State
// For map, you need to initialize it before you can add an item to it.
// Adding an item to a nil map will cause a panic.
states = make(map[string]State)
// Or use th
// states = map[string]state{}
// --- Add an item ---
ca := State{
name: "California",
abbreviation: "CA",
population: 39512223,
}
states["CA"] = ca
fmt.Println(states)
// --- Get an item ---
// Basic
state := states["CA"]
fmt.Println(state)
// Returns zero value ie. {"", "", 0} (if the item is a value) and nil (if the item is a pointer)
// if an item isn't found.
state = states["MA"]
fmt.Println(state)
// Test for existence. You can also replace state with _ given we are not interested in the value.
state, ok := states["CA"]
fmt.Printf("does CA exist? %s %t\n", state, ok)
// --- Iterate the map ---
ma := State{
name: "Massachusetts",
abbreviation: "MA",
population: 6892503,
}
states["MA"] = ma
// Order isn't guaranteed.
for key, item := range states {
fmt.Printf("key: %s, item: %v\n", key, item)
}
// --- Remove an item ---
delete(states, "CA")
_, ok = states["CA"]
fmt.Printf("does CA exist? %t\n", ok)
// --- Length of map ---
fmt.Printf("length of map %d\n", len(states))
}