|
1 | 1 | // All material is licensed under the Apache License Version 2.0, January 2004
|
2 | 2 | // http://www.apache.org/licenses/LICENSE-2.0
|
3 | 3 |
|
4 |
| -// Sample program to show how to declare and initialize a map |
5 |
| -// using a map literal and delete a key. |
| 4 | +// Sample program to show how maps behave when you read an |
| 5 | +// absent key. |
6 | 6 | package main
|
7 | 7 |
|
8 | 8 | import "fmt"
|
9 | 9 |
|
10 |
| -// user defines a user in the program. |
11 |
| -type user struct { |
12 |
| - name string |
13 |
| - surname string |
14 |
| -} |
15 |
| - |
16 | 10 | func main() {
|
17 | 11 |
|
18 |
| - // Declare and initialize the map with values. |
19 |
| - users := map[string]user{ |
20 |
| - "Roy": {"Rob", "Roy"}, |
21 |
| - "Ford": {"Henry", "Ford"}, |
22 |
| - "Mouse": {"Mickey", "Mouse"}, |
23 |
| - "Jackson": {"Michael", "Jackson"}, |
24 |
| - } |
| 12 | + // Create a map to track scores for players in a game. |
| 13 | + scores := make(map[string]int) |
25 | 14 |
|
26 |
| - // Iterate over the map. |
27 |
| - for key, value := range users { |
28 |
| - fmt.Println(key, value) |
29 |
| - } |
| 15 | + // Read the element at key "anna". It is absent so we get |
| 16 | + // the zero-value for this map's value type. |
| 17 | + score := scores["anna"] |
30 | 18 |
|
31 |
| - // Delete the Roy key. |
32 |
| - delete(users, "Roy") |
| 19 | + fmt.Println("Score:", score) |
33 | 20 |
|
34 |
| - fmt.Println("=================") |
| 21 | + // If we need to check for the presence of a key we use |
| 22 | + // a 2 variable assignment. The 2nd variable is a bool. |
| 23 | + score, ok := scores["anna"] |
35 | 24 |
|
36 |
| - // Find the Roy key. |
37 |
| - u, found := users["Roy"] |
| 25 | + fmt.Println("Score:", score, "Present:", ok) |
| 26 | + |
| 27 | + // We can leverage the zero-value behavior to write |
| 28 | + // convenient code like this: |
| 29 | + scores["anna"]++ |
| 30 | + |
| 31 | + // Without this behavior we would have to code in a |
| 32 | + // defensive way like this: |
| 33 | + if n, ok := scores["anna"]; ok { |
| 34 | + scores["anna"] = n + 1 |
| 35 | + } else { |
| 36 | + scores["anna"] = 1 |
| 37 | + } |
38 | 38 |
|
39 |
| - // Display the value and found flag. |
40 |
| - fmt.Println("Roy", found, u) |
| 39 | + score, ok = scores["anna"] |
| 40 | + fmt.Println("Score:", score, "Present:", ok) |
41 | 41 | }
|
0 commit comments