Search⌘ K

Puzzle 10 Explanation: Simple Append

Explore the mechanics of the append function in Go slices by understanding slice structure, length, and capacity. Learn why append sometimes modifies the original array and other times creates a new one, enhancing your grasp of Go's memory management with slices.

We'll cover the following...

Try it yourself

Try executing the code below to see the result for yourself.

Go (1.16.5)
package main
import (
"fmt"
)
func main() {
a := []int{1, 2, 3}
b := append(a[:1], 10)
fmt.Printf("a=%v, b=%v\n", a, b)
}

Explanation

We’ll need to dig a bit into how slices are implemented and how append works to understand why we seed this output.

If we look at src/runtime/slice.go in the Go source code, we will see:

Go (1.16.5)
type slice struct {
array unsafe.Pointer
len int
cap int
}

Above, slice is a struct with three fields. We use array as a pointer to the underlying array that holds the data. Next, ...