DEV Community

Cover image for Golang Maps
tcs224
tcs224

Posted on

Golang Maps

In the Go programming language there are maps, these have nothing to do with real world maps.

Maps in Golang associates a value to a key, you can see this as a table or set with pairs. A value can be retrieved using the key. This idea comes from hash map in computer science.

In a (hash) map, there are pairs of (key,values). For every value, there is one key. You can map a string to an int like this:

var m = make(map[string]int)

This create a map (string -> int) and initialises it.

Example

In this example we define a mapping of string to int. Then we create one pair and output it.

package main

import (
    "fmt"
)

func main() {
    var m = make(map[string]int)
    m["Apple"] = 1
    fmt.Println(m["Apple"])
}

The program outputs

$ go run example.go
1

You can define multiple key,value mappings in your map.

    m["Apple"] = 1
    m["Berry"] = 2
    m["Cherry"] = 3

If you want to iterate over the entire map, you can use this for loop:

for key, value := range m {
    fmt.Println("Key:", key, "Value:", value)
}

Other mappings

A map can also be a set of int to string pairs.

var m = make(map[int]string)

In the example below we use that for months:

package main

import (
    "fmt"
)

func main() {
    var m = make(map[int]string)
    m[1] = "January"
    m[2] = "February"
    m[3] = "March"
    for key, value := range m {
        fmt.Println("Key:", key, "Value:", value)
    }
}

You can also map int to int, consider this example:

var m = make(map[int]int)
m[1] = 1359
m[2] = 4639       
m[3] = 1234

Related links:

Top comments (0)