Skip to content

Day 010 — Slice Tricks: Filter, Insert, Delete, Copy in Place

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

🎯 Learning Objective

Apply the canonical slice idioms for filtering, inserting, deleting, and copying — and know which preserve order or allocate.

📚 Topics

  • Filter in place with s[:0]
  • Insert / delete (order-preserving vs fast)
  • copy semantics

📖 Reading / Sources

📝 Notes

  • Filter in place: out := s[:0] starts an empty slice sharing s's storage; re-append the keepers. Zero allocation, but it overwrites s → [[filter-in-place]].
  • Delete (ordered): append(s[:i], s[i+1:]...) shifts the tail left over index i — O(n), preserves order.
  • Delete (fast/unordered): s[i] = s[len(s)-1]; s = s[:len(s)-1] — O(1) swap-and-truncate, order lost.
  • Insert: grow by one, copy(s[i+1:], s[i:]) to shift right, then set s[i]. The one-liner append(s[:i], append([]T{v}, s[i:]...)...) works but allocates a temp.
  • copy(dst, src) copies min(len(dst), len(src)) elements and returns that count — it never grows dst.
  • Standard library (Go 1.21+) covers most of these: slices.Delete, slices.Insert, slices.Clone, slices.Contains, slices.Index → prefer them over hand-rolling → [[slices-package]].
  • After deleting, the now-unused tail elements still hold references; for pointer/large element types, zero them (or use slices.Delete, which does) to avoid memory leaks → [[memory-leak]].

💻 Code Examples

// Filter in place (keep evens), no allocation:
out := s[:0]
for _, v := range s {
    if v%2 == 0 {
        out = append(out, v)
    }
}
s = out

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

🏋️ Exercises / Practice

Exercise Status Link
Dedup (slice + set) exercises/month-01/week-2/dedup

🐛 Mistakes Made

  • Used fast-delete where order mattered → output scrambled. Switched to the ordered shift.
  • Forgot copy won't extend dst; sized dst too small and silently lost elements.

❓ Open Questions

  • When is filtering into a fresh slice better than in place? (When you must keep the original — in place destroys it.)

🧠 Active Recall (answer without looking)

  1. Q: Order-preserving delete of index i?
    A

s = append(s[:i], s[i+1:]...) — shifts the tail left; O(n). 2. Q: What does copy(dst, src) return, and how many elements does it move?

A

It returns the number copied = min(len(dst), len(src)); it never grows dst.

🪶 Feynman Reflection

Slice edits are really just shuffling elements within (or copying out of) a backing array. Insert shoves the tail right; ordered delete pulls it left; fast delete swaps the hole with the last element. s[:0] lets me rewrite a slice over itself.

🕳️ Knowledge Gaps

  • Benchmarking in-place vs allocating filters — defer to the testing/benchmark week.

✅ Summary

I can filter, insert, delete (both ways), and copy slices idiomatically, and I'll reach for the slices stdlib package first.

⏭️ Next Steps / Prep for Tomorrow

  • Day 011: maps and sets, comma-ok, and ordered iteration.

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

Suggested commit: feat(examples): slice tricks filter/insert/delete/copy (day 010)