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¶
- Learning Go ch.3 (Composite Types)
- Go Blog — Slices: usage and internals
- Tour of Go — Slices
📝 Notes¶
- An array's length is part of its type:
[3]intand[4]intare 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 acap. 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)ormake([]T, len, cap)allocates a backing array; the slice literal[]T{...}does the same implicitly.- Slice expression
s[low:high]yieldslen = 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).nilslices are safe torangeandappendto; prefervar s []Tover[]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
lenandcapwere always equal — they diverge afters[:n]ormakewith a cap. - Tried to compare two slices with
==→ compile error (onlynilcomparison is allowed).
❓ Open Questions¶
- When does
appendreuse vs reallocate the backing array? (Tomorrow.)
🧠 Active Recall (answer without looking)¶
- 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
appenduses (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
appendgrows, and the aliasing gotchas that follow.
| Time spent | Difficulty | Confidence |
|---|---|---|
| 90 min | 🟦🟦⬜⬜⬜ | 🟦🟦🟦⬜⬜ |
Suggested commit: feat(examples): arrays and slice basics, len/cap (day 008)