Slices are views. Arrays are values. Know the difference.
<aside> 🔗
Deep Dive: Arrays & Slices in Go Notes — full nuances, memory mechanics, edge cases
</aside>
| Aspect | Array [N]T |
Slice []T |
|---|---|---|
| Size | Fixed at compile time | Dynamic |
| Assignment | Deep copy (all data) | Shallow copy (header only) |
| Comparison | ✅ == works |
❌ Only nil |
| Map Key | ✅ Yes | ❌ No |
| Zero Value | Usable {0,0,0} |
nil |
| Memory | Stack (usually) | Header: stack, Data: heap |
var a [3]int
var b [4]int
a = b // Compile error! [3]int ≠ [4]int
func modify(arr [3]int) {
arr[0] = 999 // Only modifies local copy
}
Fix: Pass pointer *[3]int or use a slice.
visited := make(map[[2]int]bool)
visited[[2]int{0, 0}] = true
// Internally:
type slice struct {
ptr *T
len int
cap int
}
The slice header is copied, but the backing array is shared.