Appending with append
- Go course
- Beginner
- Lesson 43/90
- 4 min
Learn to add elements to a slice with the append function.
Appending with append
append adds one or more elements to the end of a slice and returns the new slice; the result must always be assigned to a variable:
var sepet []string
sepet = append(sepet, "elma")
sepet = append(sepet, "armut", "kiraz")
diger := []string{"muz", "üzüm"}
sepet = append(sepet, diger...)
fmt.Println(len(sepet)) // 5If capacity runs out, append allocates a new, larger array and moves the elements there.
Reserving capacity up front
If you know how many elements will be added, reserving capacity with make([]T, 0, n) avoids repeated growth copies:
kareler := make([]int, 0, 5)
for i := 1; i <= 5; i++ {
kareler = append(kareler, i*i)
}
fmt.Println(kareler, cap(kareler)) // [1 4 9 16 25] 5make([]int, 5) instead makes a slice of length 5 filled with zeros; appending to it starts at the 6th element.
Practice Even numbers
Append the even numbers from 1 to 10 with append to a slice started with make([]int, 0, 5). Print the slice and its capacity.
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func main() {
ciftler := make([]int, 0, 5)
for i := 1; i <= 10; i++ {
if i%2 == 0 {
ciftler = append(ciftler, i)
}
}
fmt.Println(ciftler, cap(ciftler))
}Expected output
[2 4 6 8 10] 5
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What happens if you write <code>append(s, 4)</code> without assigning the result?
- A compile error: the result is unused Correct answer
- 4 is appended to s
- Nothing, it passes silently
- A panic
Explanation: append returns a value and Go treats an unused append result as an error; the correct form is s = append(s, 4).
2 Append a slice
a = append(a, b____)
a = append(a, b...)
Explanation: b... passes the second slice's elements to append one by one.
3 Code and result
| Term | Meaning |
|---|---|
append(nil, 1) |
[1] |
append([]int{1}, 2, 3) |
[1 2 3] |
make([]int, 0, 5) |
len 0, cap 5 |
append(make([]int, 2), 7) |
[0 0 7] |