Senior
What is the difference between arrays and slices in Go?
sobes.tech AI
Answer from AI
Arrays in Go have a fixed length, which is set at declaration and cannot be changed. They store elements contiguously in memory and are passed by value, meaning they are copied when passed to functions.
Slices are dynamic structures that describe a part of an array. They contain a pointer to the array, a length, and a capacity. Slices allow working with mutable sequences of elements and are passed by reference, which is more efficient.
Example:
var arr [3]int = [3]int{1, 2, 3} // fixed-length array
var s []int = arr[:] // slice referencing the entire array
s = append(s, 4) // adding an element to the slice (creates a new array if capacity is exhausted)
The main difference is that arrays are fixed in size and copied when passed, while slices are dynamic and more flexible to use.