Slices are views. Arrays are values. Know the difference.

<aside> 🔗

Deep Dive: Arrays & Slices in Go Notes — full nuances, memory mechanics, edge cases

</aside>


Arrays vs Slices: Quick Comparison

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

Arrays: Key Points

Size is Part of the Type

var a [3]int
var b [4]int
a = b  // Compile error! [3]int ≠ [4]int

Passed by Value (Full Copy)

func modify(arr [3]int) {
    arr[0] = 999  // Only modifies local copy
}

Fix: Pass pointer *[3]int or use a slice.

Can Be Map Keys

visited := make(map[[2]int]bool)
visited[[2]int{0, 0}] = true

Slices: Key Points

Slice = Header (ptr, len, cap)

// Internally:
type slice struct {
    ptr *T
    len int
    cap int
}

The slice header is copied, but the backing array is shared.

Assignment Shares Data