Skip to main content
InterviewHubPRO
Section Overview
Q2

Question 2 of 50

Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)

4%
Golang & Concurrency (50 Qs)•Part 1: Go Language Core, Memory & Runtime Internals (1 - 15)

Slices vs. Arrays in Go: What is the Slice Header, how does slice growth work, and what is memory aliasing?

senior LevelCode ExampleData Structures

In Simple Words:

  • Array: A fixed-length, contiguous sequence of elements. In Go, an array's length is part of its type ([5]int and [10]int are completely distinct types). Arrays are passed by value (copying all elements).
  • Slice: A dynamically sized view over an underlying array.

Slice Header (24 bytes on 64-bit architecture):

  1. Data: Pointer to the underlying array.
  2. Len: Current number of elements in the slice (len(s)).
  3. Cap: Maximum capacity before reallocation is required (cap(s)).

Growth Algorithm: When append() exceeds Cap:

  • In Go 1.18+, if current capacity is $< 256$, it doubles ($2 imes$).
  • For $> 256$, it grows smoothly by $approx (cap + 3 imes 256) / 4$ (around $1.25 imes$) to prevent excessive memory waste.
  • Memory Aliasing Hazard: Slicing an existing slice (sub := original[0:2]) shares the underlying array. Mutating sub[0] mutates original[0]! Use full slice expressions original[0:2:2] or copy() to isolate memory.
go
// Demonstrating slice header and memory sharing
orig := []int{1, 2, 3, 4, 5}
sub := orig[1:3] // points to same backing array!
sub[0] = 99      // orig[1] is now 99!

// Safe copy avoiding memory leak
safeCopy := make([]int, len(sub))
copy(safeCopy, sub)