Golang / Golang Internals and Memory Management Interview Questions
What is the internal structure of a Go slice and how does it differ from an array?
A Go array is a fixed-length, value-type sequence of elements stored contiguously in memory. Its length is part of its type: [5]int and [6]int are distinct types. Arrays are copied entirely when passed to functions.
A Go slice is a lightweight descriptor — a three-field struct that lives on the stack and points into an underlying array on the heap. The three fields are:
| Field | Type | Meaning |
|---|---|---|
| ptr | unsafe.Pointer | Pointer to the first element of the backing array |
| len | int | Number of elements accessible through the slice |
| cap | int | Total elements in the backing array from ptr onward |
// Array — fixed, value type
arr := [5]int{1, 2, 3, 4, 5}
arrCopy := arr // full copy of all 5 ints
// Slice — descriptor pointing to arr's backing storage
s := arr[1:4] // s.ptr = &arr[1], s.len = 3, s.cap = 4
fmt.Println(len(s), cap(s)) // 3 4
// Modifying through the slice modifies the backing array
s[0] = 99
fmt.Println(arr) // [1 99 3 4 5] — arr is mutated!
// Make allocates a fresh backing array
fresh := make([]int, 3, 6) // len=3, cap=6, new backing array
// Nil slice — zero value; all three fields are zero
var nilSlice []int
fmt.Println(nilSlice == nil, len(nilSlice)) // true 0Because a slice is just a small header, passing a slice to a function is cheap — only the three-field struct is copied, not the underlying array. However, this means the function sees the same backing array and can mutate its elements. To avoid unintended sharing, use copy() or append() on a new slice.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
