sajad torkamani

Define a map

A map is a collection of key value pairs.

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"])
}

Here we define m as a map where the keys are a string and the values are a Vertex.

You can create map literals too:

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

Insert / update an element in map

m[key] = elem

Retrieve element

elem = m[key]

Delete element

delete(m, key)

Test if key is present

elem, ok = m[key]

If key is present in m, elem is the value and ok is true.

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

Tagged: Golang