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) }
More Related questions...