notexOPENOverview
Notex/Languages/Reading and Writing a Map
01.21LESSON 21 OF 33 · 1 MIN READ

Reading and Writing a Map

Always free to read

Let’s look at a short program that declares, writes to, and reads from a map. You can run the program in Example 2-10 on The Go Playground.

Example 2-10. Using a map

totalWins := map[string]int{}
totalWins["Orcas"] = 1
totalWins["Lions"] = 2
fmt.Println(totalWins["Orcas"])
fmt.Println(totalWins["Kittens"])
totalWins["Kittens"]++
fmt.Println(totalWins["Kittens"])
totalWins["Lions"] = 3
fmt.Println(totalWins["Lions"])

When you run this program, you’ll see the following output:

1
0
1
3

You assign a value to a map key by putting the key within brackets and using = to specify the value, and you read the value assigned to a map key by putting the key within brackets. Note that you cannot use:= to assign a value to a map key.

When you try to read the value assigned to a map key that was never set, the map returns the zero value for the map’s value type. In this case, the value type is an int, so you get back a 0. You can use the ++ operator to increment the numeric value for a map key. Because a map returns its zero value by default, this works even when there’s no existing value associated with the key.

Progress is saved on this device.
KEEP EXPLORING

One note leads to another.

Back to the library →
⌕
Search across the entire library ⌘ K