Maps
Maps are Go+’s built-in associative data type (sometimes called hashes or dicts in other languages).
Map foundations
Use make(map[key-type]val-type)
to create an empty map.
Set key/value pairs using typical name[key] = val
syntax.
Printing a map with e.g. println
will show all of
its key/value pairs.
Get a value for a key with name[key]
.
The builtin len
returns the number of key/value
pairs when called on a map.
The builtin delete
removes key/value pairs from
a map.
The optional second return value when getting a
value from a map indicates if the key exists
in the map. This can be used to disambiguate
between missing keys and keys with zero values
like 0
or ""
. Here we didn’t need the value
itself, so we ignored it with the blank identifier
_
.
Map literals in Go+ style
map[string]int
map[string]float64
map[string]interface{}
map[int]interface{}
type of empty map is map[string]interface{}
Map literals in Go style
You can also declare and initialize a new map in the same line with the following syntax.
{“Hello”: 1, “xsw”: 3}
{“Hello”: 1, “xsw”: 3.4}
{“Hello”: 1, “xsw”: “Go+”}
{1: 1.4, 3: “Go+”}
{}
Next example: Structs