8. Tricky Slices

The Core Problem

When you use append(), it can either:

  • Reuse the existing underlying array (if there's room)

  • Create a new array (if it's full)

The tricky part is you can't always predict which one will happen, which leads to surprising bugs.

Let's Start Simple: What is Capacity?

slice := make([]int, 3, 8)
//                   ^  ^
//                   |  |
//              length  capacity
  • Length = how many elements are currently in the slice (3)

  • Capacity = how much total space is allocated in the underlying array (8)

Think of it like a parking lot:

  • Length = cars currently parked (3 cars)

  • Capacity = total parking spaces (8 spaces)

  • You have 5 empty spaces available

Example 1: Why It Works

Visual representation:

Now append to create b:

What happens:

Since a was full (length = capacity), append creates a new array for b. They're completely separate now!

Then:

Result:

βœ… Everyone has their own array. No surprises!

Example 2: The Trap

Visual representation:

Now append to create j:

What happens:

Key point: They're sharing the same underlying array!

Now the dangerous part:

What happens:

❌ The 5 overwrote the 4! Both j and g now show 5 because they're looking at the same array.

The Memory Address Proof

Same address = same underlying array = changes affect both!

Why This Happens

The problem:

  • append(otherSlice, element) might reuse otherSlice's array

  • You assign the result to someSlice (different variable)

  • Now someSlice and otherSlice secretly share an array

  • Changes to one affect the other!

circle-check

Real-World Analogy

Imagine you have a notebook with 10 pages, but only 3 are written on:

Dangerous way:

Both notebook2 and notebook3 point to the same physical notebook, so they see the same page 4!

Safe way:

Only one variable, one notebook, no confusion!

Questions to Check Your Understanding

chevron-right1. If a slice has len=5 and cap=10, will append create a new array?hashtag

No, it will reuse the existing array because there's room (5 empty spaces left).

chevron-right2. If a slice has len=10 and cap=10, will append create a new array?hashtag

Yes, it's full, so append must create a bigger array.

chevron-right3. Why is b = append(a, x) dangerous?hashtag

If `a` has spare capacity, `b` will share `a`'s underlying array, so changes can affect both unexpectedly.