Let's talk about Maps in Go
Tags: go
Published: 2019-11-24 19:09:31

---
title: Let's talk about Maps in Go
published: true
description: In this article we're going to learn how to use Maps in Go.
tags: golang, go
cover_image: https://images.unsplash.com/photo-1503437313881-503a91226402?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2978&q=80
---

### Introduction

One of the most used and versatile data structures in programming is [Hash Tables](https://en.wikipedia.org/wiki/Hash_table) 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](https://golang.org/doc/effective_go.html#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`:

```go
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:

```go
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:

```go
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:

```go
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:

```go
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`:

```go
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.

```go
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.

```go
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)

```go
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:

```go
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 you to understand how use them in your Go apps.

Happy coding 👋🏽.