Slices
A slice wraps an array with three values: pointer, length, capacity. Cheap to pass, growable via append. The most-used data structure in Go — pay attention to aliasing and capacity behaviour.
Create, grow, slice, copy, gotchas
EXAMPLE
package main
import "fmt"
func main() {
// 1) Create
nums := []int{1, 2, 3, 4, 5} // literal
var empty []int // nil slice — len=0, cap=0
pre := make([]int, 5) // [0,0,0,0,0]
cap10 := make([]int, 0, 10) // empty, capacity 10
fmt.Println(len(nums), cap(nums))
// 2) Append — re-assign the return value
nums = append(nums, 6, 7, 8)
fmt.Println(nums, len(nums), cap(nums))
// 3) Slice expression — VIEW into the same backing array
sub := nums[1:4] // [2, 3, 4]
sub[0] = 99 // mutates nums too!
fmt.Println(nums)
// 4) Three-index slice — control capacity, prevent aliasing surprise
safe := nums[1:4:4] // len=3, cap=3 — append allocates new array
safe = append(safe, 100)
fmt.Println(nums, safe) // nums unchanged
// 5) Copy — independent slice
dst := make([]int, len(nums))
copy(dst, nums)
dst[0] = -1
fmt.Println(nums, dst)
// 6) Delete an index (no built-in — use append)
nums = append(nums[:2], nums[3:]...)
// 7) Insert at index
nums = append(nums[:2], append([]int{77}, nums[2:]...)...)
// 8) Pre-allocate when you know the size — avoids reallocations
out := make([]int, 0, len(input))
for _, x := range input {
if x > 0 { out = append(out, x) }
}
// 9) Range — i is index, v is COPY of the element
for i, v := range nums {
v *= 2 // doesn't modify nums[i]
nums[i] = v // this does
}
// 10) nil vs empty slice
var n []int
e := []int{}
fmt.Println(n == nil, e == nil) // true, false
fmt.Println(len(n), len(e)) // 0, 0 — both safe to range over
}
Why it matters
“Slice of slice mutates the original” is the most common Go surprise. Reach for the three-index slice (a[low:high:max]) when you want to hand out a view that can’t accidentally mutate parents.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Example
Example
nums := []int{1, 2, 3}
nums = append(nums, 4)
fmt.Println(nums, len(nums), cap(nums))
Try it Yourself »
Exercise
Append to a slice.
nums =
(nums, 4)
Six letters.
Discussion
Loading…