Home »
Golang
Update and Add Map Elements in Go
Last Updated : May 27, 2025
In Go, you can add new key-value pairs to a map or update existing ones using the assignment syntax. If the key already exists, its value will be updated; if not, a new entry will be added.
Adding New Elements to a Map
You can use the assignment operator to add a new key-value pair to the map.
Example
This example demonstrates how to add elements to a map:
package main
import "fmt"
func main() {
cities := map[string]string{
"NY": "New York",
"LD": "London",
}
// Adding new elements
cities["TK"] = "Tokyo"
cities["SY"] = "Sydney"
fmt.Println(cities)
}
When executed, this program outputs:
map[LD:London NY:New York SY:Sydney TK:Tokyo]
Updating Existing Elements in a Map
If a key already exists in the map, assigning a new value to it updates the value.
Example
This example updates the value of an existing key:
package main
import "fmt"
func main() {
stock := map[string]int{
"Pen": 50,
"Pencil": 100,
}
// Updating value of an existing key
stock["Pen"] = 75
fmt.Println("Updated stock:", stock)
}
When executed, this program outputs:
Updated stock: map[Pen:75 Pencil:100]
Combined Addition and Update
You can use the same assignment approach for both adding new keys and updating existing ones.
Example
This example performs both operations:
package main
import "fmt"
func main() {
scores := map[string]int{
"Alice": 90,
"Bob": 85,
}
// Updating existing key
scores["Alice"] = 95
// Adding new key
scores["Charlie"] = 88
fmt.Println(scores)
}
When executed, this program outputs:
map[Alice:95 Bob:85 Charlie:88]
Exercise
Select the correct answer for each question about adding and updating map elements in Go.
- How do you add a new key-value pair to a map in Go?
- What happens when you assign a value to an existing key in a Go map?
- Which statement is true about updating and adding in Go maps?
Advertisement
Advertisement