What is the difference between an array and a slice in Go?
Last updated
An array has a fixed length that is part of its type, while a slice is a flexible, growable view over an underlying array: in practice you almost always use slices.
Array: fixed size, value type:
[3]intand[4]intare distinct types; length is compile-time fixed.Assigning or passing an array copies all its elements.
Slice: dynamic view, reference-like:
A slice is a small header of three fields: pointer to backing array, length, and capacity.
Copying a slice copies the header but shares the same underlying array, so mutations are visible across copies.
Growth and operations:
Slices support
appendand reslicing (s[1:3]); arrays do not grow.len()andcap()apply to slices; arrays only have a fixed length.
Gotcha: Two slices from the same array share memory: editing one can change the other.
[lang:go]
arr := [3]int{1, 2, 3} // array, fixed length 3
copy := arr // full copy
copy[0] = 99 // arr[0] still 1
sl := []int{1, 2, 3} // slice
view := sl // shares backing array
view[0] = 99 // sl[0] is now 99 too
- https://go.dev/doc/effective_go
- https://riteeksrivastava.medium.com/how-slices-internally-work-in-golang-a47fcb5d42ce
- https://go.dev/blog/slices-intro
- https://go.dev/blog/generic-slice-functions
- https://medium.com/@MSaeidSedighi/arrays-and-slices-in-go-c4eece502ad2
- https://medium.com/@koliv5936/arrays-vs-slices-in-go-a-complete-guide-beginner-to-pro-89f0623fe428
- https://medium.com/@itz.aman.av/slices-vs-arrays-in-go-the-practical-guide-12f359051dcf
- https://medium.com/@piyushraj4598/interview-questions-for-golang-part7-391f63e1aca1