Golang: Map (collection of pairs)

By Xah Lee. Date: .

Map is a unordered collection of key value pairs. Similar to dictionary, hashtable, associative array, in other languages.

Each key value pair is called an element.

Syntax of Map Type

Syntax of the map type is:

map[key_type_name]value_type_name

package main

import "fmt"
import "reflect"

func main() {

        // syntax of map type.
        var mm map[string]int

        fmt.Println(reflect.TypeOf(mm)) // map[string]int
}

Create Map, Literal Expression

package main

import "fmt"

func main() {

        var mm = map[string]int{"a": 1, "b": 2}

        fmt.Println(mm) // map[a:1 b:2]
}

Create Map with make

package main

import "fmt"

func main() {

        var mp = make(map[string]int)

        mp["a"] = 1
        mp["b"] = 2

        fmt.Println(mp) // map[a:1 b:2]
}

set value, add key

m[k] = v → sets value v to key k in map.

package main

import "fmt"

func main() {

        var mm = map[string]int{"a": 1, "b": 2}

        // set value to existing key
        mm["a"] = 9
        fmt.Println(mm) // map[a:9 b:2]

        // if key don't exist, add it
        mm["c"] = 8
        fmt.Println(mm) // map[a:9 b:2 c:8]

}

get value

m[k] → returns 2 values. First value is the value of key k in map m. Second value is true if the key exist, else false.

When a key does not exist, the first value is the “zero value”. That is, 0 for number type, false for boolean, "" (empty string) for string type.

package main

import "fmt"

func main() {

        var mm = map[string]int{"a": 1, "b": 2}

        // get
        var x = mm["a"]
        fmt.Println(x) // 1

        // returns 2 values. second is true if exist, else false
        var y, z = mm["b"]
        fmt.Println(y, z) // 2 true

        // returns 2 values. second is true if exist, else false
        var h1, h2 = mm["c"]
        fmt.Println(h1, h2) // 0 false

}

delete key

delete(m, k) → delete the key k in m. if key doesn't exist, do nothing.

package main

import "fmt"

func main() {

        var mm = map[string]int{"a": 1, "b": 2}

        // delete a key
        delete(mm, "a")
        fmt.Println(mm) // map[b:2]

        // if key doesn't exist, delete does nothing
        delete(mm, "9")
        fmt.Println(mm) // map[b:2]

}

Reference

The Go Programming Language Specification - The Go Programming Language#Map_types

The Go Programming Language Specification - The Go Programming Language#Deletion_of_map_elements