Go EP 18: Slice Is Basically an Array Wrapper
When you create a slice, you're really just making a 'window' into an existing array. So, any changes you make to the slice can also change the underlying array and vice versa.
Unlike arrays, slices are a bit more flexible from a user perspective since they can resize dynamically.
When you create a slice, you're really just making a 'window' into an existing array. So, any changes you make to the slice can also change the underlying array and vice versa.
func main() {
array := [6]int{0, 1, 2, 3, 4, 5}
slice := array[1:3]
fmt.Println(slice, len(slice), cap(slice))
}
// Output:
// [1 2] 2 5
This shared reference can lead to some surprising outcomes if you're not fully aware of how it works.
The internal structure of a slice is kind of like a small struct, with just the pointer, length, and capacity. It’s pretty simple, which means slices can sometimes be allocated on the stack, though they often end up on the heap—especially when they outgrow their original capacity
type slice struct {
array unsafe.Pointer
len int
cap int
}
When you append
elements to a slice and exceed its capacity, Go automatically allocates a new, larger array, copies the existing elements, and updates the slice to point to this new array.
One thing about slices is that you can 'slice' them further without copying any data.
It just creates a new slice header that points to the same underlying array. So, you’re not duplicating memory, you’re just creating a different view into the same data.
Go's slice growth strategy is designed to balance performance and memory usage.
Initially, the capacity doubles to accommodate growth, but as the slice becomes larger, the growth rate slows to avoid excessive memory allocation.
But there’s something to watch out for, memory leaks.
If a slice still points to a big array, even if you're only using a small part of it, the entire array stays in memory. So, it’s worth being mindful of that when working with slices.
If you're interested in diving deeper into the content, you can follow the links https://victoriametrics.com/blog/go-slice/ to read the full posts.