add a key-value pair to a map in go

In Go language, we can add a key-value pair to a map using the following syntax:

main.go
map[key] = value
17 chars
2 lines

Here, the map is the name of the map variable to which we want to add a key-value pair. key is the key that we want to add and value is the value associated with that key.

Let's see an example of how to add a key-value pair to a map in Go:

main.go
package main

import "fmt"

func main() {
    // declaring and initializing a map
    studentAgeMap := map[string]int{
        "John": 20,
        "Emily": 21,
        "Adam": 22,
    }

    // adding a new key-value pair to the map
    studentAgeMap["Bob"] = 18

    // printing the map
    fmt.Println(studentAgeMap)
}
321 chars
19 lines

In the above code, we have declared and initialized a map studentAgeMap. Then we have added a new key-value pair to the map using the assignment operator =. Finally, we printed the complete map using the fmt.Println() function.

Output:

main.go
map[Adam:22 Bob:18 Emily:21 John:20]
37 chars
2 lines

gistlibby LogSnag