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
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...
