Maps (Key-Value Pairs)
Maps are hash-table mappings that store key-value pairs. In Go, maps require explicit initialization using the make function before you can write values to them.
1 Map Initialization and the Comma-OK Idiom
Key map properties include:
- make(): Maps must be initialized using the `make()` function or a map literal. Writing values to an uninitialized (nil) map causes a runtime panic.
- Comma-OK Idiom: Accessing a non-existent key in a Go map returns its zero value without error. To verify whether a key actually exists, use the **comma-ok** assignment syntax: `val, ok := scores["Alice"]`. If `ok` is true, the key exists.
2 Map Operations Code
Let's run a program declaring maps, inserting items, and verifying keys using the comma-ok idiom:
Go — Maps
▶ Run Code
package main
import "fmt"
func main() {
// Initialize map using make
scores := make(map[string]int)
scores["Alice"] = 95
scores["Bob"] = 88
fmt.Println("Scores Map: ", scores)
// Comma-ok verification
val, ok := scores["Charlie"]
if ok {
fmt.Printf("Charlie's score: %d\n", val)
} else {
fmt.Println("Charlie's score does not exist in the map!")
}
// Delete key
delete(scores, "Bob")
fmt.Println("After deleting Bob: ", scores)
}
3 Code Challenge
Challenge: Write a program that maps product names (strings) to their prices (float64). Add three products. Update the price of one product, delete another, and print the map. Use the comma-ok idiom to verify if the deleted product was removed.