Slices Cheatsheet

Arrays vs Slices

  • Array: [5]int{1, 2, 3, 4, 5} (Fixed size)
  • Slice: []int{1, 2, 3} (Dynamic size)

Creation

  • Make: make([]T, len, cap)
  • Literal: []string{"A", "B"}
  • Sub-slice: s[1:4] (Low inclusive, high exclusive)

Functions

  • len(s): Current length.
  • cap(s): Total capacity of underlying array.
  • append(s, val): Returns new slice with added element.
  • copy(dst, src): Copies elements from one slice to another.

Variadic Functions

  • Definition: func f(args ...type)
  • Unpacking: f(mySlice...)

Iteration

for i, v := range slice {
    // i is index, v is a COPY of the value
}

Key Rules

  • Slices are references; arrays are values.
  • Modifying a slice element modifies the underlying array.
  • Always re-assign the result of append: s = append(s, x).
  • Use make with capacity to avoid unnecessary memory allocations.