Map Operations
m[key] = value
value := m[key]
value, ok := m[key]
delete(m, key)
length := len(m)
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
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create stock and infer the type
stock := map[string]int{"pens": 10}
stock["pens"] = 15
stock["pencils"] = 20
// Print the values followed by a newline
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.
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
// Every Go file belongs to a package; main builds an executable
package main
// Import the fmt package
import "fmt"
// main is where the program starts running
func main() {
// Short declaration: create inventory and infer the type
inventory := map[string]int{"a": 1, "b": 2, "c": 3}
// Print the values followed by a newline
fmt.Println("entries:", len(inventory))
delete(inventory, "a")
// Print the values followed by a newline
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: