Maps
Create and set values
Use make or a literal. Keys must be comparable types.
ages := map[string]int{
"Ada": 28,
"Lin": 22,
}
ages["Sam"] = 30
fmt.Println(ages["Ada"])
Check if a key exists
The two-value form tells you whether the key was present.
age, ok := ages["Kai"]
if !ok {
fmt.Println("not found")
} else {
fmt.Println(age)
}
Delete a key
delete removes a key if it exists.
delete(ages, "Lin")
fmt.Println(ages)
Map tips
- Ranging over a map has no fixed order
- Never write to a nil map—initialize first
- Maps are reference-like: assignments share the same map
- Choose key types carefully; structs work if all fields are comparable
Comments
One comment per signed-in account. Comments are saved with this page’s URL.