Puzzle 10 Explanation: Simple Append
Understand how to use append in Go.
We'll cover the following...
We'll cover the following...
Try it yourself
Try executing the code below to see the result for yourself.
Press + to interact
Go (1.16.5)
package mainimport ("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.Pointerlen intcap int}
Above, slice
is a struct with three fields. We use array
as a pointer to the underlying array that holds the data. Next, ...