Slices
A slice is a view of an array: a pointer, a length, and a capacity. Most Go sequences are slices. They grow with append, they share storage when you reslice, and the zero slice is nil.
Detailed Explanation
[]int is the type you actually use for a list of integers. It is not an array. It is a three-word header that points at an array that may be larger than len. s[i] is the ith live element. s[lo:hi] is a new header over the same array, with a new length.
The header is copied, the array is shared. Passing s to a function copies the pointer, length, and capacity. The callee can change s[i] and the caller sees it. The callee cannot change the caller's len unless it returns a new header. That is why append must be assigned: s = append(s, v).
Nil vs empty. var s []int is nil: s == nil is true, len and cap are 0, range is a no-op, append works. s := []int{} is empty and not nil. JSON encodes nil as null and empty as []. Prefer nil until you know you need a non-nil empty slice.
Slicing. s[1:3] has length 2. Capacity is from the start of the new slice to the end of the original capacity. s[1:3:3] (full slice expression) also clips capacity, which stops a later append from overwriting the original array's later elements. Use the three-index form when you hand a subslice to code that may append.
Bounds. s[i] panics if i < 0 or i >= len(s). Capacity does not make out-of-len indexes legal. s[lo:hi] panics if the indexes are not 0 <= lo <= hi <= cap(s).
What it costs. A slice header is cheap to copy. The array is the allocation. append may allocate a larger array and copy. Range over a slice of large structs copies each element into the iteration variable; for i := range s avoids that. Prefer slices over linked lists and over arrays in APIs.
Code Examples
package main
import "fmt"
func main() {
s := []int{10, 20, 30}
t := s[1:3]
t[0] = 99
fmt.Println(s) // [10 99 30] — shared array
s = append(s, 40)
fmt.Println(s, len(s), cap(s))
}func grow(s []int, v int) []int {
return append(s, v) // caller must assign
}func clip(s []int) []int {
return s[1:3:3] // cap == len, append will allocate
}Common Gotchas
Forgetting `s = append(s, v)` drops the new header
if `append` reallocated, the caller still holds the old array.
Subslices share the array
mutating a reslice mutates the original. Copy when you need independence.
Nil and empty differ for JSON and `== nil`
both have length 0.
`s[i]` uses `len`, not `cap`
unused capacity is not indexable.