Golang Working with Maps

Golang Working with Maps

Maps in golang are one of the built-in data structures. Data is stored in the form of key and value. In other languages these are called as hashes or dict.

  • A map is an unordered collection of key-value pairs.

Note: we can execute the golang code online at https://play.golang.org/

Map initialization

package main

import "fmt"

var employee = map[string]string{"John": "EMP001", "Sandy": "EMP002"}

func main() {
    fmt.Println(employee)
}
// output: map[John:EMP001 Sandy:EMP002]

Empty Map declaration

package main

import "fmt"

func main() {
    // maps using syntax
    var codes = map[string]int{}

    // maps using make function
    var codes = make(map[string]int)
}

create map with initial data

package main

import "fmt"

func main() {
    alphabets := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
    fmt.Println(alphabets)
    // output: map[a:1 b:2 c:3 d:4]
}

we have initialized alphabets map with initial data

add a new key to the map in golang

package main

import "fmt"

func main() {
    alphabets := map[string]int{}
    alphabets["a"] = 1
    alphabets["b"] = 2
    fmt.Println(alphabets)
    // output: map[a:1 b:2]
}

update a key value of a map

package main

import "fmt"

func main() {
    alphabets := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
    // update value of "c" to 100
    alphabets["c"] = 100
    fmt.Println(alphabets)
    // output: map[a:1 b:2 c:100 d:4]
}

delete a key from golang map

  • We can delete the key form a golang map using built-in function delete
  • delete function takes first parameter as map and second parameter as key
package main

import "fmt"

func main() {
    alphabets := map[string]int{"a": 1, "b": 2, "c": 3, "d": 4}
    // delete key "c"
    delete(alphabets, "c")
    fmt.Println(alphabets)
    // output: map[a:1 b:2 d:4]
}

find if map has a key or not

Let's a quick example to find if key exists and delete it.

package main

func main () {
    var sessions = map[string] chan int{};
    sessions["moo"] = make (chan int);
    _, ok := sessions["moo"];
    if ok {
        delete(sessions, "moo");
    }
}

Finding length of a map

We use the bulit-in len function to find the length of the map

package main

import "fmt"

func main() {
    alphabets := map[string]int{}
    fmt.Println("length = ", len(alphabets))
    // output: length =  0
    alphabets["a"] = 1
    fmt.Println("length = ", len(alphabets))
    // output: length = 1
}

Iterate over a Map

  • Let's create a week days map and iterate over it.
package main

import "fmt"

func main() {
    weekdays := map[string]int{
        "sunday": 0,
        "monday": 1,
        "tuesday": 2,
        "wednesday": 3,
        "thursday": 4,
        "friday": 5,
        "saturday": 6,
    }
    for day, index := range weekdays {
        fmt.Println("key:", day, "value:", index)
    }
}

Output

key: sunday value: 0
key: monday value: 1
key: tuesday value: 2
key: wednesday value: 3
key: thursday value: 4
key: friday value: 5
key: saturday value: 6

Get all keys from a golang map as an array

  • There is no built-in function to get all keys or values from a map.
  • To get the keys or values from the maps we need to create an array, iterate over the map and append the keys and/or values to the array.
  • Let's see an example below.
package main

import "fmt"

func main() {
    weekdays := map[string]int{
        "sunday": 0,
        "monday": 1,
        "tuesday": 2,
        "wednesday": 3,
        "thursday": 4,
        "friday": 5,
        "saturday": 6,
    }

    days := []string{}
    indexes := []int{}

    for day, index := range weekdays {
        days = append(days, day)
        indexes = append(indexes, index)
    }
    fmt.Println(days)
    // output: [monday tuesday wednesday thursday friday saturday sunday]
    fmt.Println(indexes)
    // output: [1 2 3 4 5 6 0]
}

Merge two maps in golang

  • To merge maps in golang we need to create a third map and iterate over the first and second maps and update the third map.
package main

import "fmt"

func merge(ms ...map[string]string) map[string][]string {
    res := map[string][]string{}
    for _, m := range ms {
        for k, v := range m {
            res[k] = append(res[k], v)
        }
    }
    return res
}

func main() {
    m1 := map[string]string{"id_1": "val_1"}
    m2 := map[string]string{"id_2": "val_2"}
    m3 := map[string]string{"id_1": "val_3"}

    res := merge(m1, m2, m3)
    fmt.Println(res)
    // output: map[id_1:[val_1 val_3] id_2:[val_2]]
}
  • In the above code we have written a function to merge multiple maps into a single map.