Golang / GoLang Basics Interview Questions
How does append() work internally in Go? When does it allocate new memory?
append adds elements to a slice. When there is spare capacity in the backing array, it writes directly into it and increments the length — no allocation. When capacity is exhausted, it allocates a new, larger array, copies all elements, and returns a new slice header. This is why you must always assign the return value of append.
s := make([]int, 3, 5) // len=3, cap=5, backing array has 2 spare slots
fmt.Println(len(s), cap(s)) // 3 5
s = append(s, 10) // len=4, cap=5 — no allocation (has room)
s = append(s, 20) // len=5, cap=5 — no allocation (fills last slot)
s = append(s, 30) // len=6, cap>=10 — REALLOCATES! new backing array
fmt.Println(len(s), cap(s)) // 6 10 (capacity grew to ~2x)
// Sub-slice shares backing array — subtle bug territory
a := []int{1, 2, 3, 4, 5}
b := a[1:3] // [2 3] — shares backing array with a
fmt.Println(cap(b)) // 4 (from position 1 to end of a's array)
b = append(b, 99) // writes to a[3]! No reallocation needed
fmt.Println(a) // [1 2 3 99 5] — a was modified!
// FIX: use copy to get an independent slice
b2 := make([]int, len(a[1:3]))
copy(b2, a[1:3]) // independent backing array
b2 = append(b2, 99) // safe — doesn't affect a
// Pre-allocate when final length is known — avoids repeated reallocation
result := make([]int, 0, len(input)) // cap=len(input), no mid-loop alloc
for _, v := range input {
result = append(result, v*2)
}
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...
