1 minute read

Go Maps

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.

pradeep:~$cat maps.go 
package main

import "fmt"

type Vertex struct {
	Lat, Long float64
}

var m map[string]Vertex

func main() {
	m = make(map[string]Vertex)
	m["Bell Labs"] = Vertex{
		40.68433, -74.39967,
	}
	fmt.Println(m["Bell Labs"])
}
pradeep:~$go run maps.go 
{40.68433 -74.39967}

Map literals are like struct literals, but the keys are required.

pradeep:~$cat map-literals.go 
package main

import "fmt"

type Vertex struct {
	Lat, Long float64
}

var m = map[string]Vertex{
	"Bell Labs": Vertex{
		40.68433, -74.39967,
	},
	"Google": Vertex{
		37.42202, -122.08408,
	},
}

func main() {
	fmt.Println(m)
}
pradeep:~$go run map-literals.go 
map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]

If the top-level type is just a type name, you can omit it from the elements of the literal.

pradeep:~$cat another-map.go 
package main

import "fmt"

type Vertex struct {
	Lat, Long float64
}

var m = map[string]Vertex{
	"Bell Labs": {40.68433, -74.39967},
	"Google":    {37.42202, -122.08408},
}

func main() {
	fmt.Println(m)
}
pradeep:~$go run another-map.go 
map[Bell Labs:{40.68433 -74.39967} Google:{37.42202 -122.08408}]

Insert or update an element in map m:

m[key] = elem

Retrieve an element:

elem = m[key]

Delete an element:

delete(m, key)

Test that a key is present with a two-value assignment:

elem, ok = m[key]

If key is in m, ok is true. If not, ok is false.

If key is not in the map, then elem is the zero value for the map’s element type.

Note: If elem or ok have not yet been declared you could use a short declaration form:

elem, ok := m[key]
pradeep:~$cat mutating-maps.go 
package main

import "fmt"

func main() {
	m := make(map[string]int)

	m["Answer"] = 42
	fmt.Println("The value:", m["Answer"])

	m["Answer"] = 48
	fmt.Println("The value:", m["Answer"])

	delete(m, "Answer")
	fmt.Println("The value:", m["Answer"])

	v, ok := m["Answer"]
	fmt.Println("The value:", v, "Present?", ok)
}

pradeep:~$go run mutating-maps.go 
The value: 42
The value: 48
The value: 0
The value: 0 Present? false
Back to Top ↑