Data Structures - Arrays, Slices, Maps
The Memory Leak That Cost Us $2,000
var allLogs []string // Growing forever!
func processLogBatch(logs []string) {
allLogs = append(allLogs, logs...) // Memory leak!
// Process logs
sendToElasticsearch(allLogs)
}func processLogBatch(logs []string) {
// Process only current batch
sendToElasticsearch(logs)
// logs goes out of scope, garbage collected
}Arrays: Fixed-Size Collections
Array Declaration
Arrays Are Values
Array Limitations
Slices: Dynamic Arrays
Slice Declaration
Slice Internals
Length vs Capacity
Append: Growing Slices
Basic Append
Append Multiple Values
Capacity Growth
Pre-allocate When Possible
Slicing Slices
Create Sub-slices
The Leak I Had
Copy Function
Partial Copy
Copy Overlapping Slices
Maps: Key-Value Pairs
Map Declaration
Map Operations
Zero Value for Missing Keys
Iterate Over Map
Real-World Example: Word Counter
Map of Slices
Maps Are Reference Types
Practical Example: Cache Implementation
Comparing Slices and Maps
Common Pitfalls
1. Forgetting to Assign Append
2. Range Loop Variable Reuse
3. Modifying Map While Iterating
Your Challenge
Key Takeaways
What I Learned
Last updated