DEV Community

Cover image for Let's talk about Maps in Go
Gustavo Castillo
Gustavo Castillo

Posted on • Updated on

Let's talk about Maps in Go

#go

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 in a 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[]
}
Enter fullscreen mode Exit fullscreen mode

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]
}
Enter fullscreen mode Exit fullscreen mode

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]
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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]
}
Enter fullscreen mode Exit fullscreen mode

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]
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

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
    }
}

Enter fullscreen mode Exit fullscreen mode

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
    }
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

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

Happy coding 👋🏽.

Oldest comments (0)