Appending to slices
- Version
- 1.27
- Review
- Draft
Summary#
append returns a slice with additional elements. If all the new elements fit in the existing capacity, it reuses the backing array. Otherwise it allocates a new array and copies the existing elements.
Syntax#
values = append(values, next)
values = append(values, more...)
Example#
package main
import "fmt"
func main() {
values := make([]int, 1, 3)
values[0] = 10
extended := append(values, 20)
fmt.Println(len(values), len(extended))
fmt.Println(values[:2])
}
Expected output#
1 2
[10 20]
Common mistakes#
Store the returned slice to see its new length and any new backing array. When independent ownership matters, copy the elements before appending.
Version applicability#
The syntax and example work from Go 1.0.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0