Count how many times something happens by updating the value.
Go
m := make(map[string]int)
m["count"] = 1
m["count"] += 1
fmt.Println(m["count"])
Sample Program
This program shows how to store and find phone numbers by name using a map. It also checks if a name exists before printing.
Go
package main
import"fmt"
func main() {
// Create a map to store phone numbers by name
phoneBook := make(map[string]string)
// Add some entries
phoneBook["Alice"] = "123-4567"
phoneBook["Bob"] = "987-6543"// Look up a number
fmt.Println("Alice's number:", phoneBook["Alice"])
// Check if a name exists
number, found := phoneBook["Charlie"]
if found {
fmt.Println("Charlie's number:", number)
} else {
fmt.Println("Charlie not found in phone book")
}
}
OutputSuccess
Important Notes
Maps are very fast for finding data by keys compared to searching lists.
Keys in maps must be of a type that can be compared, like strings or numbers.
Maps do not keep order of items; they are for quick lookup, not sorting.
Summary
Maps store data with keys for fast lookup.
Use maps when you want to find or check data quickly by a name or label.
Always create maps with make before adding items.
Practice
(1/5)
1. Why are maps used in Go programming?
easy
A. To create graphical user interfaces
B. To perform mathematical calculations
C. To store data with keys for fast lookup
D. To handle file input and output
Solution
Step 1: Understand the purpose of maps
Maps store data in key-value pairs, allowing quick access to values using keys.
Step 2: Compare with other uses
Maps are not used for calculations, GUI, or file handling, which are handled by other packages or types.
Final Answer:
To store data with keys for fast lookup -> Option C
Quick Check:
Maps = Fast key-based data access [OK]
Hint: Maps = key-value pairs for quick data access [OK]
Common Mistakes:
Confusing maps with slices or arrays
Thinking maps are for calculations
Assuming maps handle files or UI
2. Which of the following is the correct way to create a map in Go?
easy
A. var m = map[string]int{1, 2, 3}
B. var m map[string]int = make(map[string]int)
C. var m = []int{1, 2, 3}
D. var m = make([]string, 5)
Solution
Step 1: Identify correct map creation syntax
Maps are created using make with the syntax: make(map[keyType]valueType).
Step 2: Check each option
var m map[string]int = make(map[string]int) uses make with map[string]int correctly. Options B and D create slices, and A has wrong map literal syntax.
Final Answer:
var m map[string]int = make(map[string]int) -> Option B
Quick Check:
Use make(map[key]value) to create maps [OK]
Hint: Use make(map[keyType]valueType) to create maps [OK]
Common Mistakes:
Using slice syntax instead of map
Forgetting to use make before adding items
Incorrect map literal syntax
3. What will be the output of the following Go code?