Create and update maps
Create and update maps
A map associates unique keys with values. map[string]int maps strings to integers. Use a map literal or make before inserting entries. Assign to m[key] to insert a new key or replace its value.
package main
import "fmt"
func main() { stock := map[string]int{"tea": 3, "rice": 5} stock["tea"] = 4 stock["bread"] = 2 fmt.Println(stock["tea"], stock["bread"], len(stock))}The value for tea changes without increasing the number of entries. Bread is a new key. len counts entries, not the allocated storage. The key and value types are fixed by the map type.
Expected output:
4 2 3Allocate an empty map
package main
import "fmt"
func main() { m := make(map[string]int, 10) fmt.Println(len(m)) m["books"] = 6 m["books"] += 2 fmt.Println(m["books"], len(m))}The optional size 10 is an initial space hint, not a limit or initial length. Maps grow as needed; cap is not defined for maps. Unlike slices, adding a key does not require assigning a returned map.
Expected output:
08 1Try it locally
Create an inventory with pen=2, increase pen by 3, then add paper=4. Print the two quantities and entry count.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Maps 01: Create and update maps
Check the lesson objective before moving on.
What does assigning an existing key do?
What is len(make(map[string]int, 10))?