Problem Statement
In a Google interview, you're asked to explain the fundamental differences between slices and arrays in Go, including their internal representation and growth behavior.
Key Interview Questions
Q1: What is the difference between len() and cap() of a slice?
s := make([]int, 3, 5)
fmt.Println(len(s)) // 3 - number of elements
fmt.Println(cap(s)) // 5 - underlying array sizeAnswer: len() returns the number of elements in the slice. cap() returns the capacity of the underlying array starting from the slice's first element.
Q2: If I have a slice s with len=5, cap=5, and I do s = s[:4], what is the new len and cap?
s := []int{1, 2, 3, 4, 5} // len=5, cap=5
s = s[:4]
fmt.Println(len(s), cap(s)) // 4, 5Answer: len=4, cap=5. Reslicing changes length but capacity remains the same (shares underlying array).
Q3: Explain the "Slice Header" struct structure
// reflect.SliceHeader
type SliceHeader struct {
Data uintptr // Pointer to first element
Len int // Current length
Cap int // Capacity
}Q4: What happens when you append to a slice that exceeds its capacity?
s := make([]int, 0, 4)
for i := 0; i < 10; i++ {
s = append(s, i)
fmt.Printf("len=%d cap=%d\n", len(s), cap(s))
}
// Growth: 4 -> 8 -> 16 (2x until 1024, then 1.25x)Answer: A new array is allocated with larger capacity (2x for small slices, ~1.25x for large slices), data is copied, and the old array becomes eligible for GC.
Q5: Can an array be nil?
Answer: No. Arrays are value types and cannot be nil. Slices can be nil because they're reference types (the slice header can have a nil Data pointer).
Q6: What is the "Memory Leak" risk when slicing a large array?
func leak() []byte {
big := make([]byte, 100*1024*1024) // 100MB
return big[:10] // Keeps entire 100MB in memory!
}
func noLeak() []byte {
big := make([]byte, 100*1024*1024)
result := make([]byte, 10)
copy(result, big[:10])
return result // Only 10 bytes retained
}Q7: Is it safe to concurrently read the same index of a slice?
Answer: Yes, concurrent reads are safe.
Q8: Is it safe to concurrently append to the same slice?
Answer: No! Race condition on length/capacity modification. Use mutex or channels.
Q9: What is the zero value of a slice vs a map?
Answer: Both are nil. A nil slice has len=0, cap=0. A nil map cannot be written to (panics) but can be read from (returns zero value).