Advanced Map Techniques
Concurrent Map Access
Synchronization with sync.Mutex
type SafeMap struct {
sync.Mutex
data map[string]int
}
func (m *SafeMap) Set(key string, value int) {
m.Lock()
defer m.Unlock()
m.data[key] = value
}
Using sync.Map
var concurrentMap sync.Map
// Store value
concurrentMap.Store("key", 42)
// Load value
value, exists := concurrentMap.Load("key")
Filtering Maps
func filterMap(m map[string]int, predicate func(int) bool) map[string]int {
filtered := make(map[string]int)
for k, v := range m {
if predicate(v) {
filtered[k] = v
}
}
return filtered
}
Map Merging
func mergeMaps(maps ...map[string]int) map[string]int {
merged := make(map[string]int)
for _, m := range maps {
for k, v := range m {
merged[k] = v
}
}
return merged
}
Complex Map Patterns
graph TD
A[Advanced Map Techniques] --> B[Concurrent Access]
A --> C[Transformation]
A --> D[Complex Patterns]
Deep Copying Maps
func deepCopyMap(original map[string]int) map[string]int {
copied := make(map[string]int)
for k, v := range original {
copied[k] = v
}
return copied
}
Operation |
Time Complexity |
Insertion |
O(1) |
Deletion |
O(1) |
Lookup |
O(1) |
Iteration |
O(n) |
Capacity Optimization
// Preallocate map capacity
users := make(map[string]int, 1000)
Advanced Key Types
Struct as Map Key
type Point struct {
X, Y int
}
coordinates := make(map[Point]string)
coordinates[Point{X: 10, Y: 20}] = "Origin"
Error Handling
Safe Map Access
func safeMapGet(m map[string]int, key string) (int, bool) {
value, exists := m[key]
return value, exists
}
Functional Map Manipulation
func mapValues[K comparable, V, R any](
m map[K]V,
transform func(V) R,
) map[K]R {
result := make(map[K]R)
for k, v := range m {
result[k] = transform(v)
}
return result
}
Best Practices
- Use sync.Map for concurrent scenarios
- Implement custom synchronization for complex logic
- Preallocate map capacity when possible
- Prefer type-specific maps over interface{} maps
By mastering these advanced techniques, you'll write more efficient and robust Go code with LabEx's professional approach.