Golang / GoLang Basics Interview Questions
What is the difference between arrays and slices in Go?
Arrays and slices are both ordered sequences, but they work very differently. Arrays are value types with a fixed size baked into their type; slices are reference types that provide a flexible view into an underlying array.
| Aspect | Array | Slice |
|---|---|---|
| Size | Fixed at compile time; part of the type ([5]int ≠ [6]int) | Dynamic — can grow via append |
| Passed to functions as | Full copy (value type — can be expensive) | 3-word header: pointer + len + cap (cheap) |
| Zero value | [0, 0, 0, ...] | nil (len=0, cap=0) |
| Common in practice | Rarely — mainly fixed-size buffers or keys | The everyday Go sequence type |
// Array var arr [5]int // [0 0 0 0 0] arr2 := [3]string{"a", "b", "c"} arr3 := [...]int{1, 2, 3, 4} // compiler counts: [4]int // Slice s := []int{1, 2, 3} // slice literal s2 := make([]int, 5) // len=5, cap=5, all zeros s3 := make([]int, 3, 10) // len=3, cap=10 // append â returns a NEW slice (may reallocate backing array) s = append(s, 4, 5) // [1 2 3 4 5] // Sub-slice â shares backing array! sub := s[1:4] // [2 3 4] sub[0] = 99 // changes s[1] too! // copy â independent backing array dst := make([]int, len(s)) copy(dst, s) // nil slice vs empty slice var nilSlice []int // nil â len=0, cap=0 empty := []int{} // not nil â len=0, cap=0 fmt.Println(nilSlice == nil) // true fmt.Println(empty == nil) // false
More Related questions...