slicing an array does NOT allocate memory
tags: learning dsa go programming
content
slicedata 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]aandbare separate variables on the stack, both pointing to the same data on the heap- stack memory is allocated during function
fstarts- so within the function, when
b := a[1:4]is called, it only creates newsliceHeaderstructure in the stack itself - no memory allocation!
- so within the function, when
- that’s why
slicein Go is cheap!
slicing operation does not need to allocate memory, not even for the slice header