Slice length vs. capacity in Go

Figure 1 — A three-length, six-capacity slice
Figure 2 — Updating the slice’s second element: s[1] = 1
panic: runtime error: index out of range [4] with length 3
Figure 3 — Appending an element to s
[0 1 0 2 3 4 5]
Figure 4 — Because the initial backing array is full, Go creates another array and copies all the elements.
Figure 5 — The slices s1 and s2 reference the same backing array with different lengths and capacities
Figure 6 — Because s1 and s2 are backed by the same array, updating a common element makes the change visible in both slices
Figure 7 — Appending an element to s2
Figure 8 — Appending elements to s2 until the backing array is full


About the author



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Teiva Harsanyi

Teiva Harsanyi


Software Engineer @Docker 🐳 | 📖 100 Go Mistakes author | 改善