How to initialize a map in Golang

In this shot, we will learn how to initialize a map in Golang.

A map is an unordered collection of key-value pairs, where the keys are unique.

We can initialize a map in two ways:

  1. By using make
  2. By using map literal

1. Using make

We can initialize a map using the make function provided by Golang.

Syntax

Initializing without size:

m := make(map[string]int)

Initializing with size:

m := make(map[string]int, 10)

Here, the key is of type string, and the value is of type int.

Note: Providing the size here doesn’t mean that map doesn’t grow. It only allocates the given size, but the size will grow if we add more elements to it.

Example

package main
//import format package
import(
"fmt"
)
//program execution starts here
func main(){
//initialize map using make
m := make(map[string]int)
//add an item
m["apples"] = 20
//display the map
fmt.Println(m)
}

2. Using map literal

We can initialize a map using the map literal provided by Golang.

Syntax

m := map[string]int{"key":value}

Here, the key is of type string and the value is of type int.

We can provide key-value pairs, separated by the comma , in flower braces {}.

Example

package main
//import format package
import(
"fmt"
)
//program execution starts here
func main(){
//initialize map using map literal
m := map[string]int{"oranges":30}
//display the map
fmt.Println(m)
}

Free Resources