Map Manipulation Techniques
Core Map Operations
graph TD
A[Map Operations] --> B[Adding Elements]
A --> C[Accessing Elements]
A --> D[Updating Elements]
A --> E[Deleting Elements]
A --> F[Checking Existence]
1. Adding Elements
Basic Element Addition
// Creating a map
scores := make(map[string]int)
// Adding elements
scores["Alice"] = 95
scores["Bob"] = 88
2. Accessing Elements
Safe Element Retrieval
// Simple access
bobScore := scores["Bob"]
// Safe access with existence check
if score, exists := scores["Charlie"]; exists {
fmt.Println("Charlie's score:", score)
} else {
fmt.Println("Charlie not found")
}
3. Updating Elements
Direct Update
// Update existing element
scores["Alice"] = 97
// Conditional update
if _, exists := scores["Bob"]; exists {
scores["Bob"] += 5
}
4. Deleting Elements
Using delete() Function
// Delete a specific element
delete(scores, "Bob")
5. Advanced Manipulation Techniques
Merging Maps
func mergeMaps(map1, map2 map[string]int) map[string]int {
merged := make(map[string]int)
for k, v := range map1 {
merged[k] = v
}
for k, v := range map2 {
merged[k] = v
}
return merged
}
Map Operation Complexity
Operation |
Time Complexity |
Insert |
O(1) |
Lookup |
O(1) |
Delete |
O(1) |
Iteration |
O(n) |
6. Iterating Over Maps
Range-based Iteration
func printScores(scores map[string]int) {
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
}
7. Defensive Programming
Nil Map Handling
func safeMapOperation(m map[string]int) {
// Check if map is nil
if m == nil {
m = make(map[string]int)
}
// Perform operations
m["NewKey"] = 100
}
Filtering Map
func filterScores(scores map[string]int, threshold int) map[string]int {
filtered := make(map[string]int)
for name, score := range scores {
if score >= threshold {
filtered[name] = score
}
}
return filtered
}
9. Concurrent Map Access
graph TD
A[Concurrent Map Access] --> B[Use sync.Map]
A --> C[Mutex Protection]
A --> D[Channel-based Synchronization]
Using sync.Map
import "sync"
var concurrentMap sync.Map
func main() {
concurrentMap.Store("key", "value")
value, loaded := concurrentMap.Load("key")
}
Best Practices
- Always check map existence before accessing
- Use
make()
to initialize maps
- Be cautious with concurrent map access
- Prefer
sync.Map
for concurrent scenarios
Complete Example
package main
import "fmt"
func main() {
// Map manipulation demonstration
scores := map[string]int{
"Alice": 95,
"Bob": 88,
"Carol": 92,
}
// Update score
scores["Bob"] += 5
// Delete an entry
delete(scores, "Carol")
// Iterate and print
for name, score := range scores {
fmt.Printf("%s: %d\n", name, score)
}
}
Master these techniques with LabEx to become proficient in Go map manipulation.