Creating Slices with make and append
Creating a Slice with make
make([]Type, length) creates a slice of the given length, filled with zero values, ready to index into directly. An optional third argument sets the initial capacity separately from the length.
Example: Creating a Slice with make
package main
import "fmt"
func main() {
s := make([]int, 3)
s[0], s[1], s[2] = 1, 2, 3
fmt.Println(s)
}
Login to try C/C++/Java/PHP code in the editor
Appending Elements
append adds one or more elements to the end of a slice and returns the resulting slice, which you must assign back to a variable, because append may or may not return the same underlying array depending on whether it had room to grow.
Note: Always write 's = append(s, ...)' -- forgetting to reassign is one of the most common Go beginner bugs.
Example: Appending Elements
package main
import "fmt"
func main() {
nums := []int{1, 2}
nums = append(nums, 3, 4, 5)
fmt.Println(nums)
}
Login to try C/C++/Java/PHP code in the editor
Growing Beyond Capacity
When append needs more room than the current capacity allows, Go allocates a new, larger underlying array, copies the existing elements over, and returns a slice pointing at the new array -- which is why the old and new slice can end up independent after a big enough append.
Example: Growing Beyond Capacity
package main
import "fmt"
func main() {
s := make([]int, 0, 2)
for i := 1; i <= 5; i++ {
s = append(s, i)
fmt.Println("len:", len(s), "cap:", cap(s))
}
}
Login to try C/C++/Java/PHP code in the editor
- Ignoring append's return value, assuming it modifies the original slice variable in place -- you must reassign the result.
- Calling make([]int, 5) expecting an empty slice, when it actually creates a slice of length 5 filled with zero values.
- Appending to a slice obtained by slicing another slice and being surprised when it overwrites data in the original's underlying array.
- make([]Type, length, capacity) allocates a new slice with a given size.
- append(slice, values...) adds elements, returning a (possibly new) slice that must be reassigned.
- If a slice's capacity is exceeded, append allocates a new, larger underlying array automatically.
- make(slice, 0, n) pre-allocates capacity while keeping length 0, useful when the final size is roughly known.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: