How to Add Element to Map in Go: Simple Guide
In Go, you add an element to a map by assigning a value to a key using the syntax
mapName[key] = value. If the key does not exist, Go creates it and stores the value; if it exists, the value is updated.Syntax
The basic syntax to add or update an element in a map is:
mapName[key] = value- mapName: the map variable
- key: the key where you want to add or update the value
- value: the value you want to store at that key
This works for maps with any key and value types.
go
myMap[key] = value
Example
This example shows how to create a map, add elements to it, and print the map to see the result.
go
package main import "fmt" func main() { // Create a map with string keys and int values ages := make(map[string]int) // Add elements to the map ages["Alice"] = 30 ages["Bob"] = 25 // Update an existing element ages["Alice"] = 31 // Print the map fmt.Println(ages) }
Output
map[Alice:31 Bob:25]
Common Pitfalls
Some common mistakes when adding elements to maps in Go include:
- Trying to add elements to a
nilmap, which causes a runtime panic. - Using keys of the wrong type, which causes a compile-time error.
- Forgetting to initialize the map before adding elements.
Always initialize your map with make or a map literal before adding elements.
go
package main import "fmt" func main() { var m map[string]int // m is nil // m["key"] = 10 // This will panic: assignment to entry in nil map // Correct way: m = make(map[string]int) m["key"] = 10 fmt.Println(m) }
Output
map[key:10]
Quick Reference
| Operation | Syntax | Description |
|---|---|---|
| Add or update element | mapName[key] = value | Adds a new key or updates existing key with value |
| Initialize map | mapName := make(map[keyType]valueType) | Creates an empty map ready for use |
| Declare nil map | var mapName map[keyType]valueType | Declares a map but it is nil and cannot store elements |
Key Takeaways
Use
mapName[key] = value to add or update elements in a Go map.Always initialize maps with
make or a literal before adding elements to avoid runtime errors.Adding a value to a nil map causes a panic; initialize first.
Map keys must be of the declared key type; mismatched types cause compile errors.
Updating a key that exists simply overwrites its value.