Junior
What is the difference between slices and arrays in Go?
sobes.tech AI
Answer from AI
Arrays have a fixed length determined at creation. Slices are dynamic views of underlying arrays.
Main differences:
| Attribute | Array | Slice |
|---|---|---|
| Length | Fixed | Dynamic |
| Creation | [N]Type (N - size) |
[]Type or make([]Type, len, cap) |
| Passing | By value | By reference (to the underlying array) |
| Resizing | Not possible | Possible (using append) |
Examples:
// Declaring and initializing an array
var arr [3]int // array of 3 ints, initialized with zeros
arr2 := [2]string{"a", "b"} // array of 2 strings
// Declaring and initializing slices
var slice []int // nil slice
slice2 := []string{"x", "y", "z"} // slice of 3 strings
slice3 := make([]int, 5) // slice of 5 ints, initialized with zeros
slice4 := make([]int, 2, 5) // slice of 2 ints, initialized with zeros, capacity 5
// Slice behavior example
arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // slice referencing arr[1], arr[2], arr[3]
slice[0] = 99 // modifies arr[1]
// Resizing a slice
slice = append(slice, 100) // creates a new underlying array if current one cannot hold the element
Slices are more flexible and often used instead of arrays in Go. They provide a convenient way to work with variable-length sequences of data.