Maps are Go’s built-in associative data type (sometimes called hashes or dicts in other languages). |
|
![]() ![]() package main |
|
import "fmt" |
|
func main() { |
|
To create an empty map, use the builtin |
m := make(map[string]int) |
Set key/value pairs using typical |
m["k1"] = 7 m["k2"] = 13 |
Printing a map with e.g. |
fmt.Println("map:", m) |
Get a value for a key with |
v1 := m["k1"] fmt.Println("v1: ", v1) |
The builtin |
fmt.Println("len:", len(m)) |
The builtin |
delete(m, "k2") fmt.Println("map:", m) |
The optional second return value when getting a
value from a map indicates if the key was present
in the map. This can be used to disambiguate
between missing keys and keys with zero values
like |
_, prs := m["k2"] fmt.Println("prs:", prs) |
You can also declare and initialize a new map in the same line with this syntax. |
n := map[string]int{"foo": 1, "bar": 2} fmt.Println("map:", n) } |
Note that maps appear in the form |
$ go run maps.go map: map[k1:7 k2:13] v1: 7 len: 2 map: map[k1:7] prs: false map: map[bar:2 foo:1] |
Next example: Range.