Append and retain the returned slice
Append and retain the returned slice
append(s, values...) returns an updated slice. If the underlying array has sufficient capacity, append reuses it; otherwise it allocates a sufficiently large new array and copies the existing elements. Always keep the returned slice when you need the new length.
package main
import "fmt"
func main() { s := make([]int, 1, 3) s[0] = 5 t := append(s, 6, 7) fmt.Println(s, len(s)) fmt.Println(t, len(t), cap(t))}Appending does not change the length of the original slice variable s. Both slices refer to the same array here because capacity is sufficient. Assign s = append(s, ...) to update s itself.
Expected output:
[5] 1[5 6 7] 3 3Append multiple items and return the new value
package main
import "fmt"
func add(s []int, v int) []int { return append(s, v) }func main() { s := []int{1, 2} s = append(s, []int{3, 4}...) s = add(s, 5) fmt.Println(s, len(s))}... expands a slice as the elements to append. A function receives a copy of the slice descriptor, so return the new descriptor to the caller. Never assume a particular capacity growth factor.
Expected output:
[1 2 3 4 5] 5Try it locally
Start with []int{1}. Append 2 and then the elements of []int{3,4}. Retain the result and print it with its length.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Slices 04: Append and retain the returned slice
Check the lesson objective before moving on.
How should you retain the result of append?
When must append allocate a new underlying array?