todo Read https://go.dev/blog/maps #todo Watch https://www.youtube.com/watch?v=Tl7mi9QmLns
Map type is map[keyType]valueType
.
Init
Using map literal
Comma after the last element in the map literal is required, contrary to some other languages, where itβs recommended, but not enforced.
Using make
When you donβt know values, but know how much keys will be there, you can specify the size to improve performance.
Example
nil
, zero value
The zero value of a map is nil
.
- It has
len=0
, has no keys. - Read attempts will always return the zero value of the mapβs value type.
- Write attempts to a nil map causes a panic.
Comma ok
idiom
Go doesnβt raise an error when you try to access the key that isnβt in the map. Instead it returns a zero value of the mapβs element type. Go provides a comma ok idiom for cases when you need to know if the key is present in the map:
If key
is in m
, ok
is true
. If not, ok
is false
.
If key
is not in the map, then elem
is the zero value for the mapβs element type.
Delete from the map
If the key is not in the map or the map is nil
, nothing happens.
Empty the map
Comparison
maps
package provides maps.Equal()
and maps.EqualFunc()
.
Using maps as sets
Go doesnβt have a separate set type. You can simulate some of its features you can use maps with key for the type you want to put into set, and use the bool
for the value type.
Same idea with structs:
The advantage is that an empty struct uses zero bytes, while a boolean uses one byte. The disadvantage is that using a struct{} makes your code clumsier. You have a less obvious assignment, and you need to use the comma ok idiom to check if a value is in the set
There are also third-party libraries for that.