Skip to content

Day 008 — Arrays & Slice Basics (len/cap)

Month 1 · Week 2 · ⬅ Day 007 · Day 009 ➡ · Journal index

🎯 Learning Objective

Tell arrays and slices apart, and read a slice as a (pointer, len, cap) header over a backing array.

📚 Topics

  • Arrays: fixed size, value semantics
  • Slices: len, cap, make, slice expressions

📖 Reading / Sources

📝 Notes

  • An array's length is part of its type: [3]int and [4]int are different types. Arrays are values — assignment/passing copies every element → [[arrays]].
  • A slice is a 3-word header: a pointer to a backing array, a len, and a cap. It is a view, not the data itself → [[slice-header]].
  • len(s) = elements you can index now; cap(s) = elements available before a regrow forces a new backing array.
  • make([]T, len) or make([]T, len, cap) allocates a backing array; the slice literal []T{...} does the same implicitly.
  • Slice expression s[low:high] yields len = high-low, cap = cap(s)-low — it shares the original backing array → [[slice-aliasing]].
  • The zero value of a slice is nil (len 0, cap 0). nil slices are safe to range and append to; prefer var s []T over []T{}.

💻 Code Examples

s := make([]int, 3, 5) // len=3, cap=5
full := []int{0, 1, 2, 3, 4}
window := full[1:3]    // {1,2}; len=2, cap=4 (index 1 to end of backing array)

Full code: examples/month-01/slice-internals/main.go · Run: go run ./examples/month-01/slice-internals

🏋️ Exercises / Practice

Exercise Status Link
Inspect len/cap after slicing examples/month-01/slice-internals

🐛 Mistakes Made

  • Assumed len and cap were always equal — they diverge after s[:n] or make with a cap.
  • Tried to compare two slices with == → compile error (only nil comparison is allowed).

❓ Open Questions

  • When does append reuse vs reallocate the backing array? (Tomorrow.)

🧠 Active Recall (answer without looking)

  1. Q: What three things does a slice header hold?
    A

A pointer to the backing array, a length, and a capacity. 2. Q: Why are [3]int and [4]int not assignable to each other?

A

Array length is part of the type, so they are distinct, incompatible types.

🪶 Feynman Reflection

An array is a fixed box of N slots that you copy whole. A slice is a sticky note that points at part of some array and remembers how many slots it can see (len) and how many it could grow into (cap).

🕳️ Knowledge Gaps

  • The exact growth factor append uses (revisit Day 009).

✅ Summary

I can distinguish arrays (values, fixed size) from slices (views with len/cap) and read a slice expression's resulting len/cap.

⏭️ Next Steps / Prep for Tomorrow

  • Day 009: how append grows, and the aliasing gotchas that follow.

Time spent Difficulty Confidence
90 min 🟦🟦⬜⬜⬜ 🟦🟦🟦⬜⬜

Suggested commit: feat(examples): arrays and slice basics, len/cap (day 008)