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.

m := make(map[string]int)

Set key/value pairs using typical name[key] = val syntax.

m["k1"] = 7 m["k2"] = 13

Printing a map with e.g. println will show all of its key/value pairs.

println "map:", m

Get a value for a key with name[key].

v1 := m["k1"] println "v1: ", v1

The builtin len returns the number of key/value pairs when called on a map.

println "len:", len(m)

The builtin delete removes key/value pairs from a map.

delete m, "k2" println "map:", m

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 _.

_, exists := m["k2"] println "exists:", exists

Map literals in Go+ style

map[string]int

println {"Hello": 1, "xsw": 3}

map[string]float64

println {"Hello": 1, "xsw": 3.4}

map[string]interface{}

println {"Hello": 1, "xsw": "Go+"}

map[int]interface{}

println {1: 1.4, 3: "Go+"}

type of empty map is map[string]interface{}

println {}

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}

println map[string]int{"Hello": 1, "xsw": 3}

{“Hello”: 1, “xsw”: 3.4}

println map[string]float64{"Hello": 1, "xsw": 3.4}

{“Hello”: 1, “xsw”: “Go+”}

println map[string]interface{}{"Hello": 1, "xsw": "Go+"}

{1: 1.4, 3: “Go+”}

println map[int]interface{}{1: 1.4, 3: "Go+"}

{}

println map[string]interface{}{}

Next example: Structs