Maps are mapping keys to values. The key is then used to “unlock” the data, e. g. to give us access or the ability to overwrite the value.

When creating a map, first the data type of the key is defined. In the following code example, we set the key to be a string. Following is the type of the actual value.

type Person struct {
	Name string
	Age  int
}
 
// map[<Key-Type>]<Value-Type> 
var personMap map[string]Person
 
func main() {
	personMap = make(map[string]Person)
	personMap["CEO"] = Person{"Max", 23}
	personMap["CTO"] = Person{"John", 26}
 
 
	fmt.Println(personMap["CEO"])
}
 

”CEO” is the key, while the Person-instance is the value.

This can be rewritten to literals:

type Person struct {
	Name string
	Age  int
}
 
var personMap = map[string]Person{
	"CEO": Person{"Max", 23},
	"CTO": Person{"Kate", 26},
}
 
func main() {
	fmt.Println(personMap["CTO"])
}

Here, we turned from declaration to declaration and initialization. Actually, providing the Person-type here in the initialization is optional: “If the top-level type is just a type name, you can omit it from the elements of the literal.”

 
var personMap = map[string]Person{
	"CEO": {"Max", 23},
	"CTO": {"Kate", 26},
}

Mutating maps

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 mok 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]

Creating maps with make

To understand what makedoes, check this make and new

When creating a map with make one can’t initialize it with values directly. Instead, an empty map is created and then filled with values.

	people := make(map[string]Person)
	people["CTO"] = Person{"Max", 22}

Next chapter: Methods