Go Maps: Powerful Key-Value Stores

Maps in Go offer a versatile way to store and retrieve data based on unique keys. They are essential for building data-driven applications and provide efficient lookup operations.



Understanding Maps

A map is a collection of unordered key-value pairs. The keys must be of a comparable type (e.g., numbers, strings, structs), while the values can be of any type.

Creating Maps

There are two primary ways to create maps:

Using the map keyword

Syntax

var myMap map[keyType]valueType

Using the make function

Syntax

myMap := make(map[keyType]valueType)

Example

Code Snippet

package main

import "fmt"

func main() {
// Using map keyword
var countryCapitals = map[string]string{
"France": "Paris",
"Germany": "Berlin",
"Italy": "Rome",
}

// Using make function
populationCounts := make(map[string]int)
populationCounts["India"] = 1400000000
populationCounts["China"] = 1424000000
}

Output

Output

map[France:Paris Germany:Berlin Italy:Rome]
map[India:1400000000 China:1424000000]

Declare Maps

Maps can be declared using the var keyword or shorthand syntax.

Syntax:

Using var keyword

Syntax

var mymap = map[TypeOfKey]TypeOfValue{key1: value1, key2: value2, ...}

Shorthand syntax

Syntax

mymap := map[TypeOfKey]TypeOfValue{key1: value1, key2: value2, ...}

Example: Map Declaration

Code Snippet

package main

import "fmt"

func main() {
// Using var
var emplist = map[int]string{1: "Steve", 2: "Roy", 3: "Amar", 4: "Nancy", 5: "Abdul"}
fmt.Println(emplist)

// Shorthand syntax
empsal := map[string]int{"Steve": 60000, "Roy": 70000, "Amar": 75000, "Nancy": 60000, "Abdul": 65000} 
fmt.Println(empsal)
}

Output

Output

map[1:Steve 2:Roy 3:Amar 4:Nancy 5:Abdul]
map[Abdul:65000 Amar:75000 Nancy:60000 Roy:70000 Steve:60000]

Create Map using make() Function

The built-in make() function can be used to create an empty map by specifying the key and value type, as shown below.

Example: Create Map using make()

Code Snippet

// create an empty map
var emplist = make(map[int]string)

fmt.Println(emplist) // output: map[]

// Add members to the map
emplist[1] = "Steve"
emplist[2] = "Roy"
emplist[3] = "Amar"
emplist[4] = "Nancy"
emplist[5] = "Abdul"

fmt.Println(emplist) // output: [1:Steve 2:Roy 3:Amar 4:Nancy 5:Abdul]

Output

Output

map[1:Steve 2:Roy 3:Amar 4:Nancy 5:Abdul]

Valid Types for Map

The data type of a key element should be a type that can be compared using the == operator.

Valid Key Types: Numbers, string, Boolean, arrays, pointers, struct

Invalid Key Types: Functions, slices, and maps

The type of value can be of any type.

Access Maps

The values in a map can be retrieved by passing the key in the square bracket, e.g. map[key]. The following example retrieves map values:

Example: Retrieve Map Values

Code Snippet

emplist := map[int]string{1: "Amit", 2: "Rajesh", 3: "Amar", 4: "Suresh", 5: "Rahul"}

fmt.Println(emplist[1]) // output: Amit
fmt.Println(emplist[2]) // output: Rajesh
fmt.Println(emplist[3]) // output: Amar
fmt.Println(emplist[4]) // output: Suresh
fmt.Println(emplist[5]) // output: Rahul
fmt.Println(emplist[15]) // output: 

Output

Output

Amit
Rajesh
Amar
Suresh
Rahul

Check If Key Exists

The map[key] returns two values: the value itself and a boolean (true or false) indicating if the specified key exists. It returns true if a key exists; otherwise, it returns false. If the specified key does not exist, then the value will be the default value of the type of value.

Example: Check Key Existence

Code Snippet

emplist := map[int]string{1: "Amit", 2: "Rajesh", 3: "Amar", 4: "Suresh", 5: "Rahul"}

// Check for an existing key
val, ok := emplist[3]
fmt.Println(val, ok) // output: Amar  true 

// Check for a non-existing key
val2, ok := emplist[7]
fmt.Println(val2, ok) // output:  false

Output

Output

Amar true
false

Add or Update Elements

You can add a new element or update an existing one in the map using map[key]. The following example updates the value of an existing key 2 and adds a new key 6 and its value to the map.

Example: Add a New Key-Value Pair

Code Snippet

emplist := map[int]string{1: "Amit", 2: "Rajesh", 3: "Amar", 4: "Suresh", 5: "Rahul"}
emplist[2] = "Arun" // update
emplist[6] = "Rakesh" // add

fmt.Println(emplist)

Output

Output

map[1: Amit 2: Arun 3: Amar 4: Suresh 5: Rahul 6: Rakesh]

Delete Map Element

Use the delete(map, key) function to remove a key-value pair from a map.

Example: Delete Element from Map

Code Snippet

emplist := map[int]string{1: "Amit", 2: "Rajesh", 3: "Amar", 4: "Suresh", 5: "Rahul"}
delete(emplist, 1)
delete(emplist, 2)

fmt.Println(emplist)

Output

Output

map[3:Amar 4:Suresh 5:Rahul]

Count of Map Elements

len() function returns the total number of elements in a map.

Example: Count Elements in Map

Code Snippet

emplist := map[int]string{1: "Amit", 2: "Rajesh", 3: "Amar", 4: "Suresh", 5: "Rahul"}
delete(emplist, 1)
delete(emplist, 2)

fmt.Println(len(emplist))

Output

Output

3

Iterating Map using for Loop

Just like arrays, you can iterate through a map using the for loop.

Example: Iterate through Map

Code Snippet

emplist := map[int]string{1: "Amit", 2: "Rajesh", 3: "Amar", 4: "Suresh", 5: "Rahul"}

for keyVar, val := range emplist {
fmt.Printf("%v : %v, ", keyVar, val)
}

Output

Output

1 : Amit, 2 : Rajesh, 3 : Amar, 4 : Suresh, 5 : Rahul,

Important Points

  • Maps are unordered, meaning the iteration order is not guaranteed.
  • Map keys must be unique.
  • Maps are reference types, so changes made to a map are reflected in all variables referencing it.

By understanding these concepts, you can effectively use maps to store and manage data in your Go programs.