Go - Map Example

In this example, we will show how to work with maps in Golang.

A map is an unordered collection of key/value pairs, where each key is unique.

Go - Map Example

Maps are created with make() function or with map literals.

The below example shows how to create a Map, print Map, get value from Map:

package main

import "fmt"

func main() {

    // To create an empty map, use the builtin make function
    m := make(map[string]int)

    // Set key/value pairs using typical name[key] = val syntax.
    m["k1"] = 1
    m["k2"] = 3
    m["k3"] = 5
    m["k4"] = 7
    m["k5"] = 9

    fmt.Println("printing map:", m)

    // Get a value for a key with name[key].
    v1 := m["k1"]
    fmt.Println("v1: ", v1)

    v5 := m["k5"]
    fmt.Println("v5: ", v5)

    // The builtin len returns the number of key/value pairs when called on a map.
    fmt.Println("len:", len(m))

    delete(m, "k2")
    fmt.Println("map:", m)

    _, prs := m["k2"]
    fmt.Println("prs:", prs)

    // You can also declare and initialize a new map in the same line with this syntax.
    n := map[string]int{"foo": 1, "bar": 2}
    fmt.Println("map:", n)
}

Output:

printing map: map[k1:1 k2:3 k3:5 k4:7 k5:9]
v1:  1
v5:  9
len: 5
map: map[k1:1 k3:5 k4:7 k5:9]
prs: false
map: map[bar:2 foo:1]

Comments