Slices
Create a slice
A slice holds a length, capacity, and a view into an underlying array.
nums := []int{10, 20, 30}
fmt.Println(nums[0], len(nums))
Append elements
append may allocate a larger array; always keep the returned slice.
nums = append(nums, 40)
fmt.Println(nums)
Slice a slice
Sub-slices share the same backing array unless you copy.
mid := nums[1:3]
fmt.Println(mid)
Slice habits
- Prefer slices over arrays for most application code
- Check
lenbefore indexing - Use
copywhen you need an independent duplicate - Nil slices are valid and have length 0
Comments
One comment per signed-in account. Comments are saved with this page’s URL.