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?
Answer: 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?
Answer: len=4, cap=5. Reslicing changes length but capacity remains the same (shares underlying array).
Q3: Explain the "Slice Header" struct structure
Q4: What happens when you append to a slice that exceeds its capacity?
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?
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).