Golang Map Tutorial

Kuldeep Singh
3 min readOct 20, 2021

--

In this article we are going to learn about maps in golang.

So the topics we are going to cover in this are these:
How we can create a map?
How to add key and values in map?
How we can update a map?
How we can get a value from map using key?
How we can delete a entry from a map?

also we are going to learn something more which is important while using maps to read and write concurrently.

Let’s start with the definition of the maps in golang

What is Map in Golang?

One of the most useful data structures in computer science is the hash table. Many hash table implementations exist with varying properties, but in general they offer fast lookups, adds, and deletes. Go provides a built-in map type that implements a hash table.

1. How we can create map?

Before Declaration and initialization of a map let’s check the syntax of the map
A type map in Go looks like this

map[keyType]valueType

keyType can be any type that is comparable and valueType also can be any type at all, including another map and interfaces as well!

I’m gonna cover three ways to declaration and initialization of a map in golang.

Let’s see

1. Using var and make function

var usersVisited map[string]int
usersVisited = make(map[string]int)

2. The Way Most of the Devs Uses and it’s easy

This approach is good to creating a map when you don’t have to add keys and values at the time of map initialization.

usersVisited := make(map[string]int)

3. When you wanted to add keys and values at the time of initialization of a map

This approach is also good when you wanted to add the values in map at the time of it’s initialization, As you can see we have created a usersVisited map with the key type string and value type is int and immediately adding key and values into it.

usersVisited := map[string]int{
"127.0.0.1": 1,
"127.0.0.2": 2,
"127.0.0.3": 3,
"127.0.0.4": 4,
}

2. How to add key and value in map

The syntax to adding the entries in a map is this.

map[keyType] = valueType

keyType can be any type and as well the valueType can be any type even map.

Example:

package main

import "fmt"

func main() {
usersVisited := map[string]int{
"127.0.0.1": 1,
"127.0.0.2": 2,
"127.0.0.3": 3,
"127.0.0.4": 4,
}
fmt.Println("map before adding new entry", usersVisited)
usersVisited["127.0.0.5"] = 5
fmt.Println("map after adding new entry", usersVisited)
}

So as you can see we have created a map and at the same time we have added entries as well and then we added new entry with the same syntax

OUTPUT:

map before adding new entry map[127.0.0.1:1 127.0.0.2:2 127.0.0.3:3 127.0.0.4:4]
map after adding new entry map[127.0.0.1:1 127.0.0.2:2 127.0.0.3:3 127.0.0.4:4 127.0.0.5:5]

To Continue Reading
Support me

Thanks for reading don’t forget to leave comment if you found this article helpful.

--

--

Kuldeep Singh
Kuldeep Singh

No responses yet