...

/

Puzzle 10 Explanation: Simple Append

Puzzle 10 Explanation: Simple Append

Understand how to use append in Go.

We'll cover the following...

Try it yourself

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

Press + to interact
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:

Press + to interact
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 ...

Access this course and 1400+ top-rated courses and projects.