AppDividend
Latest Code Tutorials

Golang Maps Tutorial With Examples | Maps in Go Explained

0

Golang Maps Tutorial With Examples | Maps in Go Explained is today’s topic. 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. Go map is an unordered collection of key-value pairs. They map keys to values. Go map keys are unique within the map while the values may or may not be the same.

Golang Maps Tutorial

Go provides another essential data type named the map which maps unique keys to values. A key is an object that you use to retrieve the value at a later date. Given a key and a value, you can store the value in a Map object. After the value is stored, you can retrieve it by using its key.

The map data structure is used for fast lookups, retrieval, and deletion of the data based on keys; that is why it is one of the most used data structures in computer science. There are also other data types available unlike maps for example arrays, structs, and slice in Golang. Let’s start our Golang maps tutorial.

Declaration and initialization of Maps in Go

A Go map type looks like the following.

map[KeyType]ValueType

where KeyType may be any comparable type (more on this later), and ValueType may be any type at all, including another map.

See the variable m is a map of string keys to int values.

var m map[string]int

Map types are reference types, like pointers or slices, and so the value of m above is nil.

A nil map has no keys. A nil map behaves like a blank map when reading. Any attempt to add keys to a nil map will result in a runtime error.

See the below code of nil variable in Go.

// hello.go

package main

import "fmt"

func main() {
	var app map[string]int
	fmt.Println(app)
	if app == nil {
		fmt.Println("app variable is nil")
	}
}

See the below output.

Golang Maps Tutorial

 

Now, let’s add the items to the nil map and see the output.

// hello.go

package main

import "fmt"

func main() {
	var app map[string]int
	app["dividend"] = 21
	fmt.Println(app)
}

See the below output.

Maps in Go Explained

 

That is why it is the requirement to initialize a map before adding items to it.

Initializing a map in Golang

We can initialize the go map using the following two ways.

  1. Initializing the map using a built-in make() function.
  2. Initializing a map using a map literal.

Let’s see one by one way to initialize the maps.

Initializing the map using the built-in make() function

You can initialize the map using a built-in make() function. You just need to pass the type of map to the make() function. See the below syntax.

var app = make(map[string]int)

Now, see the below code example.

// hello.go

package main

import "fmt"

func main() {
	var app = make(map[string]int)
	app["dividend"] = 21
	fmt.Println(app)
}

See the below output.

Initializing a map using the built-in make() function

 

See the second example.

// hello.go

package main

import "fmt"

func main() {
	app := make(map[int]string)
	app[21] = "facebook"
	app[19] = "instagram"
	app[46] = "whatapp"
	fmt.Println(app)
}

Now, run in your console and see the output. In this example, we have changed the key to integer and value to string.

Initializing the map using a map literal

A map literal is the very convenient way to initialize the map with some data. You just need to pass the key-value pairs separated by a colon inside the curly braces. See the following syntax.

var app = map[string]int{
   "k": 19,
   "l": 21,
   "a": 46,
}

Now, see the below full example code.

// hello.go

package main

import "fmt"

func main() {
	var app = map[string]int{
	   "k": 19,
	   "l": 21,
	   "a": 46,
	}
	fmt.Println(app)
}

The output is following.

Golang Maps

 

Adding items (key-value pairs) to a map

You can add new elements to the initialized map using the following syntax.

app[key] = value

We have does this in previous examples. We can add as many key/value pairs as possible.

See the following code.

// hello.go

package main

import "fmt"

func main() {
	got := make(map[int]string)
	got[1] = "ned"
	got[2] = "arya"
	got[3] = "jon"
	fmt.Println(got)
}

First, we have initialized the map and then add the three key/value pairs to the map and printed that map.

See the below output.

Adding items (key-value pairs) to a map

 

If you try to add the key that already exists in a map, then it will be overridden by the new value.

See the below code.

// hello.go

package main

import "fmt"

func main() {
	got := make(map[int]string)
	got[1] = "ned"
	fmt.Println("Before override the value")
	fmt.Println(got)
	fmt.Println("After override the value")
	got[1] = "jon"
	fmt.Println(got)
}

See the below output.

Initializing a map using a map literal

 

Deleting a key from a map in Go

The delete() function is used to delete the particular entry from the map. It requires the map and the corresponding key which is to be deleted. You can delete the entry from a map using the map key. See the following syntax.

delete(map, key)

Go map’s delete() function doesn’t return any value. Also, it doesn’t do anything if the key doesn’t exist on the map. See the following code.

// hello.go

package main

import "fmt"

func main() {
	got := make(map[int]string)
	got[1] = "ned"
	got[2] = "arya"
	got[3] = "jon"
	fmt.Println(got)
	fmt.Println("Let's delete the ned")
	delete(got, 1)
	fmt.Println(got)
}

In the above code, we have integer keys. If we want to delete an item then in the parameter we need two things.

  1. Map
  2. Key

We have used the delete() function and provide the map and key arguments to remove the ned value.

See the below output.

Deleting a key from a map in Go

 

Retrieving the value in Map

You can retrieve the value assigned to the key in a map using the syntax map[key].

If a key exists in the map, we’ll get the assigned value. Otherwise, we’ll get the 0 value of the map’s value type. See the following code.

// hello.go

package main

import "fmt"

func main() {
	got := make(map[int]string)
	got[1] = "ned"
	got[2] = "arya"
	got[3] = "jon"
	dead := got[1]
	fmt.Println(dead)
}

In the above code, we have retrieved the value ned from the map got using its key 1. We will get ned in the output. If we provide a key which does not exist in the map then it will return empty or nil.

// hello.go

package main

import "fmt"

func main() {
	got := make(map[int]string)
	got[1] = "ned"
	got[2] = "arya"
	got[3] = "jon"
	dead := got[19]
	fmt.Println(dead)
}

Here, 19 key is not present inside the map. That is why it will return nothing or ” “.

Check if the key exists in the map

When you retrieve the value assigned to the given key using the syntax map[key], it returns the additional boolean value as well which is true if the key exists in the map, otherwise false if it doesn’t exist.

So you can check for the existence of the key in the map by using the following two-value assignment syntax.

value, exist := map[key]

The boolean variable exist will be true if the key exists, if not then false otherwise. See the below code.

// hello.go

package main

import "fmt"

func main() {
	got := make(map[int]string)
	got[1] = "ned"
	got[2] = "arya"
	got[3] = "jon"
	dead, exist := got[1]
	fmt.Println(dead, exist)
}

See the below output.

Check if a key exists in a map

 

If you try to check the presence of key which not there then you will get false.

Maps are reference types

Maps are reference types and not value types. When you assign a map to the new variable, they both refer to the same underlying data structure.

Therefore changes done on the one variable will be visible to the other.

See the following code example.

// hello.go

package main

import "fmt"

func main() {
	got := make(map[int]string)
	got[1] = "ned"
	got[2] = "arya"
	got[3] = "jon"

	gameofthrones := got
	fmt.Println(got)
	fmt.Println(gameofthrones)
	fmt.Println("---Change the gameofthrones map---")
	got[4] = "Daenerys"
	fmt.Println(got)
	fmt.Println(gameofthrones)
}

In the above code, we have assigned the got map to the gameofthrones map and then modify the gameofthrones map to see if the got map is changed or not as well. See the output.

 

Maps are reference types

Here, if the one is modified the, both are modified that means maps in go is reference types.

Conclusively, Golang Maps Tutorial With Examples | Maps in Go Explained article is over.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.