To add a key-value pair to a map in Go, you can use the subscript operator.
We can add a key-value pair to a map in Go using the subscript operator, which adds an element with a specific key and value to the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.fmt.Printf
function.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Add a key-value pair using subscript operator
myMap["four"] = 4
// Print the updated map
for key, value := range myMap {
fmt.Printf("%s: %d\n", key, value)
}
}
one: 1 two: 2 three: 3 four: 4
We can add multiple key-value pairs to a map in Go using the subscript operator.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.fmt.Printf
function.package main
import "fmt"
func main() {
// Declare and initialize a map
myMap := map[string]int{
"one": 1,
"two": 2,
"three": 3,
}
// Add multiple key-value pairs using subscript operator
myMap["four"] = 4
myMap["five"] = 5
// Print the updated map
for key, value := range myMap {
fmt.Printf("%s: %d\n", key, value)
}
}
one: 1 two: 2 three: 3 four: 4 five: 5
In this tutorial, we learned How to Add a Key-Value Pair to a Map in Go language with well detailed examples.