Slices
Dynamic sequences built on arrays, including length, capacity, append, and shared backing storage.
A slice is a flexible view of part of an array. Its length is the number of elements it currently contains. Its capacity is how many elements it can hold before Go needs a larger array.
Use make to choose an initial length and capacity. append adds elements and returns the updated slice:
package main
import "fmt"
func main() {
values := make([]int, 0, 2)
values = append(values, 10, 20)
fmt.Println(len(values), cap(values)) // 2 2
values = append(values, 30)
fmt.Println(values, len(values), cap(values))
}A sub-slice shares the array with the original slice, so changing a shared element can affect both. Use copy to make an independent copy:
original := []int{1, 2, 3}
part := original[:2]
part[0] = 9
fmt.Println(original[0]) // 9
separate := make([]int, len(part))
copy(separate, part)
separate[0] = 5
fmt.Println(original[0]) // still 9In production
Use a sub-slice only when sharing its array is safe. If you know roughly how many elements you need, set a capacity with make to reduce resizing. append may create a larger array when capacity runs out, so always keep its returned slice.