Map Operations
Adding and Updating Entries
Assigning to a key with m[key] = value adds a new entry if the key doesn't exist yet, or overwrites the existing value if it does -- there's no separate insert versus update operation.
Example: Adding and Updating Entries
package main
import "fmt"
func main() {
stock := map[string]int{"pens": 10}
stock["pens"] = 15
stock["pencils"] = 20
fmt.Println(stock)
}
Login to try C/C++/Java/PHP code in the editor
Deleting Entries
The built-in delete function removes a key-value pair from a map. Calling it with a key that isn't present is perfectly safe and simply does nothing.
Note: delete() never panics, even if the key is missing -- no need to check existence first.
Example: Deleting Entries
package main
import "fmt"
func main() {
stock := map[string]int{"pens": 10, "pencils": 20}
delete(stock, "pencils")
delete(stock, "erasers") // no-op, key doesn't exist
fmt.Println(stock)
}
Login to try C/C++/Java/PHP code in the editor
Getting the Size of a Map
len() works on maps just as it does on slices and strings, returning the current number of key-value pairs stored -- it updates automatically as entries are added or removed.
Example: Getting the Size of a Map
package main
import "fmt"
func main() {
inventory := map[string]int{"a": 1, "b": 2, "c": 3}
fmt.Println("entries:", len(inventory))
delete(inventory, "a")
fmt.Println("entries after delete:", len(inventory))
}
Login to try C/C++/Java/PHP code in the editor
- Trying to delete a key that doesn't exist and expecting an error -- delete() is a safe no-op on missing keys.
- Assuming len(m) counts something other than the number of key-value pairs currently in the map.
- Using a slice or other non-comparable type (like another map) as a map key, which fails to compile since map keys must be comparable.
- Adding or updating a map entry uses the same syntax: m[key] = value.
- delete(m, key) removes an entry, and is a safe no-op if the key isn't present.
- len(m) returns the number of key-value pairs in the map.
- Map keys must be a comparable type -- strings, numbers, and structs of comparable fields all qualify.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: