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 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) }
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 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) }
RELATED TAGS
CONTRIBUTOR
View all Courses