Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)
Slices vs. Arrays in Go: What is the Slice Header, how does slice growth work, and what is memory aliasing?
senior LevelCode ExampleData Structures
In Simple Words:
- Array: A fixed-length, contiguous sequence of elements. In Go, an array's length is part of its type (
[5]intand[10]intare completely distinct types). Arrays are passed by value (copying all elements). - Slice: A dynamically sized view over an underlying array.
Slice Header (24 bytes on 64-bit architecture):
Data: Pointer to the underlying array.Len: Current number of elements in the slice (len(s)).Cap: Maximum capacity before reallocation is required (cap(s)).
Growth Algorithm:
When append() exceeds Cap:
- In Go 1.18+, if current capacity is $< 256$, it doubles ($2 imes$).
- For $> 256$, it grows smoothly by $approx (cap + 3 imes 256) / 4$ (around $1.25 imes$) to prevent excessive memory waste.
- Memory Aliasing Hazard: Slicing an existing slice (
sub := original[0:2]) shares the underlying array. Mutatingsub[0]mutatesoriginal[0]! Use full slice expressionsoriginal[0:2:2]orcopy()to isolate memory.
go
// Demonstrating slice header and memory sharing
orig := []int{1, 2, 3, 4, 5}
sub := orig[1:3] // points to same backing array!
sub[0] = 99 // orig[1] is now 99!
// Safe copy avoiding memory leak
safeCopy := make([]int, len(sub))
copy(safeCopy, sub)