Go maps
A map
is a data structure that allows to store values with arbitrary indexes called keys.
A map maps keys to values.
The zero value of a map is nil
. A nil map has no keys, nor can keys be added.
The make
function returns a map of the given type, initialized and ready for use.
A map literal in go is defined like this:
1catalog := map[int]Book{
2 1: Book{ID: 1, Title: "For the Love of Go"}
3}
so you specify the type of the key inside square brackets, and the type of the values afterwards.
If the top-level type is just a type name, you can omit it from the elements of the literal.
1catalog := map[int]Book{
2 1: {ID: 1, Title: "For the Love of Go"}
3}
Operations
To access elements, you just need to specify their key in square brackets:
1catalog[1]
To insert or update an element:
1catalog[key] = elem
To delete an element:
1delete(catalog, key)
Test that a key is present with a two-value assignment:
1val, ok := catalog[key]
ok
will return true
if key
is in the map, otherwise false
. In the latter, val
will be zero value.
1package main
2
3import "fmt"
4
5type Vertex struct {
6 Lat, Long float64
7}
8
9var m map[string]Vertex // nil
10
11func main() {
12 m = make(map[string]Vertex) // not nil
13 m["Bell Labs"] = Vertex{
14 40.68433, -74.39967,
15 }
16 fmt.Println(m["Bell Labs"])
17}
References
- John Arundel, For the Love of Go