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:
- By using
make - By using
mapliteral
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
mapdoesn’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 packageimport("fmt")//program execution starts herefunc main(){//initialize map using makem := make(map[string]int)//add an itemm["apples"] = 20//display the mapfmt.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 packageimport("fmt")//program execution starts herefunc main(){//initialize map using map literalm := map[string]int{"oranges":30}//display the mapfmt.Println(m)}