Core Collections: Slices ([]T), Maps (map[K]V) & Structs
1Concept
A Slice is a 3-word header (pointer to backing array, length, capacity). Calling append() grows capacity automatically. A Map provides O(1) hash lookups.
2Architecture Diagram
Slice Header: [ Pointer (8-byte) | Length (8-byte) | Capacity (8-byte) ]
│
▼
Backing Array: [ 10 ] [ 20 ] [ 30 ] [ ... ]3Code Example
Stage 0 Language Foundations
package main
import "fmt"
func main() {
// Dynamic Slice
numbers := make([]int, 0, 4) // len 0, cap 4
numbers = append(numbers, 10, 20, 30)
fmt.Printf("Slice: %v, Len: %d, Cap: %d\n", numbers, len(numbers), cap(numbers))
// Hash Map
cache := make(map[string]int)
cache["session_101"] = 1500
cache["session_102"] = 2800
if val, exists := cache["session_101"]; exists {
fmt.Printf("Cache Hit: %d\n", val)
}
}4Expected Output
Slice: [10 20 30], Len: 3, Cap: 4 Cache Hit: 1500
5Key Takeaways
- ✓Pre-allocate slice capacity with make([]T, 0, cap) to avoid reallocations.
- ✓Reading a missing key in a Go map returns the type's zero-value (use 'val, ok := map[key]').
- ✓Maps in Go are not thread-safe for concurrent writes (use sync.RWMutex or sync.Map).