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:
make
map
literalmake
We can initialize a map using the make
function provided by Golang.
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.
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)}
map
literalWe can initialize a map using the map
literal provided by Golang.
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 {}
.
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)}