Middle
What is the difference between an array and a slice in Go?
sobes.tech AI
Answer from AI
In Go, arrays and slices differ in several key aspects:
-
Array — a fixed-size structure, whose size is set at declaration and cannot be changed. Arrays store elements contiguously in memory.
-
Slice — a dynamic structure that is a reference to an array with additional information about length and capacity. Slices allow resizing and adding elements.
Example:
var arr [3]int = [3]int{1, 2, 3} // fixed-size array
slice := []int{1, 2, 3} // slice, can be extended
slice = append(slice, 4) // adding an element
Thus, slices are more flexible and are used more often in Go, whereas arrays are used when a fixed size and high performance are required.