Maps
https://blog.golang.org/go-maps-in-action
Table of Contents
- Basics of
map - Mimic
settype with amap - Implement a nested
mapwhich works like adefaultdictin Python
Basics of map tutorial
map[KeyType]ValueType
- Maps are reference types, so you don't need to pass maps as pointers.
- The
KeyTypemust be comparable using==. - So, types like
slicecannot be aKeyType. - The zero value for a
mapisnil. nilmapbehaves 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
okis aboolthat istrueif the key exists in the map. - When
okisfalse,xis going to be the zero value of theValueType. - As a
mapelement 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)