We add or update values in a map to store or change information. This helps keep data organized and easy to find.
0
0
Adding and updating values in Go
Introduction
When you want to save a new phone number for a contact.
When you need to change the price of an item in a store list.
When you want to keep track of scores in a game and update them.
When you want to add new settings or change existing ones in a program.
Syntax
Go
mapName[key] = value
This works for both adding a new key-value pair and updating an existing one.
If the key is new, it adds the pair. If the key exists, it changes the value.
Examples
First, we add Alice's age as 30. Then we update it to 31.
Go
ages := map[string]int{} ages["Alice"] = 30 // Add new key-value pair ages["Alice"] = 31 // Update existing value
We start with one item, then add banana and update apple's price.
Go
prices := map[string]float64{"apple": 0.99}
prices["banana"] = 0.59 // Add new item
prices["apple"] = 1.09 // Update priceSample Program
This program creates an inventory map with two items. It adds a new item 'eraser' and updates the count of 'pen'. Then it prints all items and their counts.
Go
package main import "fmt" func main() { inventory := map[string]int{"pen": 10, "notebook": 5} // Add a new item inventory["eraser"] = 3 // Update existing item inventory["pen"] = 15 fmt.Println("Inventory:") for item, count := range inventory { fmt.Printf("%s: %d\n", item, count) } }
OutputSuccess
Important Notes
If you try to update a key that does not exist, Go will add it automatically.
Maps in Go do not keep order, so items may print in any order.
Summary
Use mapName[key] = value to add or update values in a map.
Adding a new key creates a new pair; updating changes the existing value.
Maps help organize data with easy access and modification.