Last updated on Jun 20, 2021 by Suraj Sharma
In this tutorial, you will learn to create a Map of key-value pairs in Golang using the built-in make
function.
To create and initialize a map
, we call the make
function by passing the map key-value type as the first argument and 0
as the second argument.
package main
import "fmt"
func main () {
simpleMap := make(map[int]string, 0)
simpleMap[1] = "One"
simpleMap[2] = "Two"
// print the complete Map
fmt.Println(simpleMap) // map[1:One 2:Two]
// get values from Map using keys
fmt.Println(simpleMap[1]) // "One"
fmt.Println(simpleMap[2]) // "Two"
}
Refer to the next example to create a map without using the make
function
package main
import "fmt"
func main () {
anotherMap := map[int]string{
3: "Three",
4: "Four",
}
fmt.Println(anotherMap) // map[3:Three 4:Four]
}
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.