slicing an array does NOT allocate memory

tags: learning dsa go programming

content

  • slice data structure in Go:
type sliceHeader struct {
    Data *elem  // pointer to the underlying array
    Len  int
    Cap  int
}
  • we can have:
func f() {
    a := []int{1, 2, 3, 4, 5}
    b := a[1:4]
}
  • how the memory looks:
Stack:
  a: { ptr → [1 2 3 4 5], len=5, cap=5 }
  b: { ptr → [2 3 4],     len=3, cap=4 }
 
Heap:
  [1 2 3 4 5]
  • a and b are separate variables on the stack, both pointing to the same data on the heap
  • stack memory is allocated during function f starts
    • so within the function, when b := a[1:4] is called, it only creates new sliceHeader structure in the stack itself
    • no memory allocation!
  • that’s why slice in Go is cheap!

slicing operation does not need to allocate memory, not even for the slice header

research!rsc: Go Data Structures

up

down

reference