golang / tour

[mirror] A Tour of Go
BSD 3-Clause "New" or "Revised" License
1.53k stars 521 forks source link

tour: Incorrect slice capacity after appending? #1590

Closed woojinv closed 2 months ago

woojinv commented 4 months ago

Context: https://go.dev/tour/moretypes/15

After this last append:

s = append(s, 2, 3, 4)
printSlice(s) // len=5 cap=5 [0 1 2 3 4]

I would think the capacity becomes 5, but what is printed to stdout is len=5 cap=6 [0 1 2 3 4].

Is that correct?

I know there's a doubling of array capacities in Go, so does that have something to do with it?

Thanks

ALTree commented 2 months ago

Yeah, the capacity is actually increased by more than 1 to avoid quadratic behaviour on reallocations.