Array vs Slice in Go: Key Differences and Usage Guide
array has a fixed size defined at compile time, while a slice is a flexible, dynamically-sized view over an array. Slices are more commonly used because they allow easy resizing and efficient memory use without copying data.Quick Comparison
Here is a quick side-by-side comparison of arrays and slices in Go:
| Aspect | Array | Slice |
|---|---|---|
| Size | Fixed at compile time | Dynamic, can grow or shrink |
| Memory | Stores elements directly | References an underlying array |
| Declaration | var a [3]int | var s []int or s := []int{} |
| Resizing | Not possible | Can append elements dynamically |
| Usage | Less common, for fixed-size data | More common, flexible and efficient |
| Passing to functions | Copies entire array | Passes reference to underlying array |
Key Differences
Arrays in Go have a fixed size that you must specify when declaring them. This size cannot change during the program's execution, making arrays less flexible. Arrays store their elements directly, so when you pass an array to a function, the entire array is copied, which can be costly for large arrays.
Slices are built on top of arrays but provide a dynamic and flexible way to work with sequences of elements. A slice holds a reference to an underlying array, along with its length and capacity. When you pass a slice to a function, only the slice header (reference, length, capacity) is copied, not the underlying data, making it more efficient.
Slices can grow or shrink using built-in functions like append, which automatically manages the underlying array's size. This flexibility and efficiency make slices the preferred choice for most Go programs.
Code Comparison
Here is how you declare and use an array in Go to store and print three numbers:
package main import "fmt" func main() { var arr [3]int = [3]int{10, 20, 30} for i := 0; i < len(arr); i++ { fmt.Println(arr[i]) } }
Slice Equivalent
Here is the equivalent code using a slice, which is more flexible and idiomatic in Go:
package main import "fmt" func main() { s := []int{10, 20, 30} for i := 0; i < len(s); i++ { fmt.Println(s[i]) } }
When to Use Which
Choose array when you know the exact number of elements at compile time and the size will never change, such as fixed-size buffers or constants. Arrays can be useful for small, fixed collections where copying is not expensive.
Choose slice in almost all other cases because slices provide flexibility to grow or shrink, efficient memory usage by referencing arrays, and better performance when passing data around. Slices are the standard way to handle collections in Go.