Maps
In Go, maps are very similar to dictionaries in Python, or hashtables in Java.
Definition
The syntax to define a map is map[keyType]valueType {map block}
, e.g.
1 | m := map[string]string { |
The outputs of printing the above map is:
1 | map[course:Golang name:Talk Golang site:talkgolang.com twitter:talkgolang] |
The map definition can be nested, e.g. map[K1]map[K2]V
, K1
is the key, and its value is another map.
Make a map
We could create a map with make
method
1 | m2 := make(map[string]int) |
m2
is an empty map.
1 | map[] |
We can also declare an empty map with var
1 | var m3 map[string]int |
1 | map[] |
The difference is m2
is an empty map, but m3
is nil.
Traversing Map
Use for...range
to traverse a map.
1 | for k, v := range m{ |
The output will be:
1 | key = name ; val = Talk Golang ; m[k] = Talk Golang |
Note, maps are unordered. The outputs of above traversing will change each time.
Accessing element
Similar to access an item in Python’s dictionary, we use key name to access an element in the map:
1 | courseName := m["course"] |
The outputs will be
1 | Golang |
However, the key name doesn’t exist in the map, Go will return a Zero value instead of raising errors like Python
1 | causeName := m["cause"] |
The outputs will be nil
1 |
Check if the key exists at all
We could check whether the target key exists or not in the map.
1 | courseName, ok := m["course"] |
The above will output:
1 | Golang true |
If the key doesn’t exist then ok
is false
. So we could refactor as such
1 | if causeName, ok := m["cause"]; ok { |
The output will be:
1 | Key doesn't exist |
Deleting Map Values
We could delete map values with delete
method
1 | name, ok := m["name"] |
The outputs will be:
1 | Talk Golang true |
More on the key
- Go maps use hash tables, so the keys must be comparable
- All built-in go data types can be used as map keys, except for slice, map, function
To Summarize
- To create a map, we can use
make
method - To get a map value, map_name[key]
- When key doesn’t exist, we will get a Zero value as its init value
- Use
value, ok := map_name[key]
to check ifkey
exists at all - Use
delete(map_name, key)
to delete the element - Use
for...range
to traverse the map, however traversing a map is unordered