Maps
https://blog.golang.org/go-maps-in-action
Table of Contents
- Basics of
map
- Mimic
set
type with amap
- Implement a nested
map
which works like adefaultdict
in Python
Basics of map
tutorial
map[KeyType]ValueType
- Maps are reference types, so you don't need to pass maps as pointers.
- The
KeyType
must be comparable using==
. - So, types like
slice
cannot be aKeyType
. - The zero value for a
map
isnil
. nil
map
behaves like an empty map. Most operations without assignments are safe.
Declare / init a
map
Iterate over a
map
Get an element in a
map
- The second value
ok
is abool
that istrue
if the key exists in the map. - When
ok
isfalse
,x
is going to be the zero value of theValueType
. - As a
map
element is not a variable, you cannot take its address.
Delete(remove) an element from a
map
delete()
doesn't return anything.delete()
will do nothing if the specified key doesn't exist.
Mimic set
type with a map
howto
- http://www.gopl.io/ (4.3)
Implement a nested map
which works like a defaultdict
in Python howto
graph := make(map[string]map[string]bool)
func addEdge(from, to string) {
edges := graph[from]
if edges == nil {
edges = make(map[string]bool)
graph[from] = edges
}
edges[to] = true
}
- http://www.gopl.io/ (4.3)