Middle
What is the difference between an array and a slice in Go?
sobes.tech AI
Answer from AI
In Go, arrays and slices are different data types with different properties:
-
Array — a fixed-size sequence of elements of the same type. The size of the array is set at declaration and cannot be changed.
-
Slice — a dynamic structure that references a part of an array. Slices can change in length and automatically expand when elements are added.
Example:
var arr [3]int = [3]int{1, 2, 3} // fixed-size array
var slice []int = arr[0:2] // slice referencing part of the array
slice = append(slice, 4) // slice expands, and a new array is created if necessary
Thus, slices are convenient for working with dynamic data, while arrays are suitable when a fixed size and predictable memory layout are needed.