loading...
Cover image for Let's talk about Maps in Go

Let's talk about Maps in Go

#go
gcdcoder profile image Gustavo Castillo ・3 min read

Introduction

One of the most used and versatile data structures in programming is Hash Tables it is used to save an unordered collection of data in key: value format in which all the keys are unique and the value associated with every key can be retrieved, deleted or updated in constant time no matter how large the hash table. The way we use it in Go is through Maps.

What is a Map?

A map is a reference to a hash table, and a map type is defined map[K]V, where K and V are the types of its keys and values. Some characteristics about maps are:

  • All keys in a given map are of the same type.
  • All values ina given map are of the same type.
  • Keys do not need to be of the same type as the values.
  • Key type K must be comparable using == (to check if a given key already exists in the map).
  • Floating-point numbers are comparable, but it's a bad idea to use them as keys.

Creating Maps

Create a map using the built-in function make:

package main

import "fmt"

func main() {
    // mapping from strings to ints
    ages := make(map[string]int)
    fmt.Println(ages) // map[]
}

Use a map literal to create a map with some initial data:

package main

import "fmt"

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }
    fmt.Println(ages) // map[gustavo:26 jhon:20]
}

Use built-in function make and subscript notation:

package main

import "fmt"

func main() {
    ages := make(map[string]int)
    ages["gustavo"] = 26
    ages["jhon"] = 20

    fmt.Println(ages) // map[gustavo:26 jhon:20]
}

Access to Maps values

Maps values are accessed through subscript notation:

package main

import "fmt"

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }

    fmt.Println(ages["gustavo"]) // 26
}

Update a Map value

We use subscript notation and assign a new value to the key:

package main

import "fmt"

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }

    ages["gustavo"] = 30

    fmt.Println(ages["gustavo"]) // 30
}

Delete a Map value

Use built-in function delete:

package main

import "fmt"

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }

    delete(ages, "gustavo") // remove element ages["gustavo"]

    fmt.Println(ages) // map[jhon:20]
}

What if the element isn't in the map?

A map lookup using a key that isn't present returns the zero value for its type.

package main

import "fmt"

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }
    ages["karla"] = ages["karla"] + 1

    fmt.Println(ages) // map[gustavo:26 jhon:20 karla:1]
}

Accessing a map element using subscript notation always returns a value as we saw in the previous example, but some time you need to know whether the element was really there or not.

package main

import "fmt"

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }

    age, ok := ages["karla"]

    if !ok { // "karla" is not a key in this map, age == 0
        fmt.Println("Element is not in the map")
        fmt.Printf("The age is = %d", age) // 0
    }
}

Print all Map values (not in order)

package main

import (
    "fmt"
)

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }

    for key, value := range ages {
        fmt.Println(key, value) // gustavo 26 jhon 20
    }
}

Print Map in order

We must sort the keys explicitly, for example:

package main

import (
    "fmt"
    "sort"
)

func main() {
    ages := map[string]int{
        "gustavo": 26,
        "jhon": 20,
    }
    var keys []string
    for age := range ages {
        keys = append(keys, age)
    }

    sort.Strings(keys)

    for _, age := range keys {
        fmt.Printf("%s\t%d\n", age, ages[age]) // gustavo 26 jhon 20
    }
}

Conclusion

Maps are really helpful so I hope it helps to understand how use them in your Go apps.

Happy coding 👋🏽.

Posted on by:

gcdcoder profile

Gustavo Castillo

@gcdcoder

I'm a web developer I won't fix your computer >:(

Discussion

pic
Editor guide