Map
Maps in Go can be created via the make
function or via the map
syntax.
The following creates a map where the keys are strings
and the values are integers
:
var m1 map[string]int = make(map[string]int)var m2 map[string]int = map[string]int{ "one": 1, "two": 2,}
Accessing values
Section titled “Accessing values”You can access values in maps using array brackets:
m := map[string]int{ "one": 1, "two": 2,}fmt.Println(m["one"]) // prints 1fmt.Println(m["two"]) // prints 2
If the key does not exist, it will return the zero value of the value type:
m := map[string]int{ "one": 1, "two": 2,}fmt.Println(m["three"]) // prints 0
Luckily the lookup also returns a boolean indicating if the key exists in the map:
m := map[string]int{ "one": 1, "two": 2,}
v, exists := m["three"]fmt.Println(v) // prints 0fmt.Println(exists) // prints false
Adding values
Section titled “Adding values”You can add values to a map using the same syntax as accessing values:
m := make(map[string]int)m["one"] = 1m["two"] = 2fmt.Println(m) // prints map[one:1 two:2]
Deleting values
Section titled “Deleting values”You can delete values from a map using the delete
function:
m := map[string]int{ "one": 1, "two": 2,}delete(m, "one")fmt.Println(m) // prints map[two:2]
Iterating over maps
Section titled “Iterating over maps”You can use the range
keyword to iterate over maps.
As said, iteration order is not guaranteed!
m := map[string]int{ "one": 1, "two": 2,}for k, v := range m { fmt.Printf("Key: %s, Value: %d\n", k, v)}
This will likely print:
Key: one, Value: 1Key: two, Value: 2
The order will vary between different runs of the program.