Sage-Code Laboratory
index<--

Go Tutorial

A "map" is a data type that is like a hash table with two columns: key and a value. It is similar to a Python dictionary. Keys of a map can be string or numbers. The value can be any data type. All values must have the same type.

Maps

This is how a "map" declaration look like:

var x map[T] type

Where T is a type of the key and type is the type of the values.

Example:

//file map_type.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"])
}

Notes:

Map literals

A map literal is a notation that describe all members of a maps that can be used to initialize a map variable. This literal notation is using nested braces { } to define the collection elements. Map literals are like struct literals and the keys are required.

//file map_literal.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)
}

Alternative

You can omit the type from the elements of the literal. This is alternative simplified sintax:

//map_alternative.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)
}

Mutating Maps

In next example we demonstrate several operations using a map "m".

//file map_mutation.go
package main

import "fmt"

func main() {
    // declare a map m using type inference operator ":="   
    m := make(map[string]int)

    // create a new element in the map
    m["Answer"] = 42
    fmt.Println("The value:", m["Answer"])

    // create a new element in the map
    m["Answer"] = 48
    fmt.Println("The value:", m["Answer"])

    // remove element from the map
    delete(m, "Answer")
    fmt.Println("The value:", m["Answer"])

    // search for map element by name
    v, ok := m["Answer"]
    fmt.Println("v = ", v)    
    
    // expected: false
    fmt.Println("The Answer is present?", ok)
}

Output:

The value: 42
The value: 48
The value: 0
The Answer is present? false

Read next: Control Flow