go-tutorial

Go Maps

A map is a collection of key-value pairs that are not in any particular order. It converts keys into values. Within a map, the keys are unique, but the values may not be.

The map data structure is used for quick key-based data lookups, retrieval, and deletion. In computer science, it is one of the most often used data structures.

A built-in map type is available in Go. We’ll learn how to use Golang’s built-in map type in this tutorial.

Declaring a map

A map is declared using the following syntax –

var m map[KeyType]ValueType

For example, Here is how you can declare a map of string keys to int values –

var m map[string]int

The zero value of a map is nil. A nil map has no keys. Moreover, any attempt to add keys to a nil map will result in a runtime error.

Let’s see an example –

package main
import "fmt"

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

	// Attempting to add keys to a nil map will result in a runtime error
	// m["one hundred"] = 100
}


# Output

map[]
m is nil

If you uncomment the statement m[“one hundred”] = 100, the program will generate the following error –

panic: assignment to entry in nil map

It is, therefore, necessary to initialize a map before adding items to it.

Initializing a map

Using the built-in build() function to create a map

The built-in build() function can be used to create a map. Simply supply the map’s type to the make() function, as seen in the example below. The function will return a map that has been initialised and is ready to use –

// Initializing a map using the built-in make() function
var m = make(map[string]int)

Let’s see a complete example –

package main
import "fmt"

func main() {
	var m = make(map[string]int)

	fmt.Println(m)

	if m == nil {
		fmt.Println("m is nil")
	} else {
		fmt.Println("m is not nil")
	}

	// make() function returns an initialized and ready to use map.
	// Since it is initialized, you can add new keys to it.
	m["one hundred"] = 100
	fmt.Println(m)
}


# Output

map[]
m is not nil
map[one hundred:100]

2. Using a map literal to start a map

A map literal is a quick and easy way to populate a map with data. Simply place the key-value pairs separated by a colon inside curly braces, like shown –

var m = map[string]int{
	"one": 1,
	"two": 2,
	"three": 3,
}

Note that the last trailing comma is necessary, otherwise, you’ll get a compiler error.

Let’s check out a complete example –

package main
import "fmt"

func main() {
	var m = map[string]int{
		"one":   1,
		"two":   2,
		"three": 3,
		"four":  4,
		"five":  5, // Comma is necessary
	}

	fmt.Println(m)
}

# Output

map[one:1 two:2 three:3 four:4 five:5]

You can also create an empty map using a map literal by leaving the curly braces empty –

// Initialize an empty map
var m = map[string]int{}

The above statement is functionally identical to using the make() function.

Adding items (key-value pairs) to a map

You can add new items to an initialized map using the following syntax –

m[key] = value

The following example initializes a map using the make() function and adds some new items to it –


package main
import "fmt"

func main() {
	// Initializing a map
	var tinderMatch = make(map[string]string)

	// Adding keys to a map
	tinderMatch["Rajeev"] = "Angelina" // Assigns the value "Angelina" to the key "Rajeev"
	tinderMatch["James"] = "Sophia"
	tinderMatch["David"] = "Emma"

	fmt.Println(tinderMatch)

	/*
	  Adding a key that already exists will simply override
	  the existing key with the new value
	*/
	tinderMatch["Rajeev"] = "Jennifer"
	fmt.Println(tinderMatch)
}

# Output

map[Rajeev:Angelina James:Sophia David:Emma]
map[Rajeev:Jennifer James:Sophia David:Emma]

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

Retrieving the value associated with a given key in a map

You can retrieve the value assigned to a key in a map using the syntax m[key]. If the key exists in the map, you’ll get the assigned value. Otherwise, you’ll get the zero value of the map’s value type.

Let’s check out an example to understand this –

package main
import "fmt"

func main() {
	var personMobileNo = map[string]string{
		"John":  "+33-8273658526",
		"Steve": "+1-8579822345",
		"David": "+44-9462834443",
	}

	var mobileNo = personMobileNo["Steve"]
	fmt.Println("Steve's Mobile No : ", mobileNo)

	// If a key doesn't exist in the map, we get the zero value of the value type
	mobileNo = personMobileNo["Jack"]
	fmt.Println("Jack's Mobile No : ", mobileNo)
}

# Output

Steve's Mobile No :  +1-8579822345
Jack's Mobile No : 

In the above example, since the key “Jack” doesn’t exist in the map, we get the zero value of the map’s value type. Since the map’s value type is string, we get ” “.

Unlike other languages, we do not get a runtime error in Golang if the key doesn’t exist in the map.

Deleting a key from a map

You can delete a key from a map using the built-in delete() function. The syntax looks like this

// Delete the `key` from the `map`
delete(map, key)

The delete() function doesn’t return any value. Also, it doesn’t do anything if the key doesn’t exist in the map.

Here is a complete example –

package main

import "fmt"

func main() {
	var fileExtensions = map[string]string{
		"Python": ".py",
		"C++":    ".cpp",
		"Java":   ".java",
		"Golang": ".go",
		"Kotlin": ".kt",
	}

	fmt.Println(fileExtensions)

	delete(fileExtensions, "Kotlin")

	// delete function doesn't do anything if the key doesn't exist
	delete(fileExtensions, "Javascript")

	fmt.Println(fileExtensions)
}

# Output

map[Python:.py C++:.cpp Java:.java Golang:.go Kotlin:.kt]
map[Python:.py C++:.cpp Java:.java Golang:.go]

Iterating over a map

You can iterate over a map using range form of the for loop. It gives you the key, value pair in every iteration –

package main
import "fmt"

func main() {
	var personAge = map[string]int{
		"Rajeev": 25,
		"James":  32,
		"Sarah":  29,
	}

	for name, age := range personAge {
		fmt.Println(name, age)
	}

}

# Output

James 32
Sarah 29
Rajeev 25

It’s worth noting that because a map is an unordered collection, its iteration order isn’t guaranteed to remain the same every time you iterate over it.

As a result, if you run the same programme numerous times, you’ll get different results each time.

RECOMMENDED ARTICLES





Leave a Reply

Your email address will not be published.