Senior
Mis on slice ja kuidas see erineb massiivist?
sobes.tech AI
Vastus AI-lt
In Go, an array is a fixed-size structure that contains elements of the same type. The size of the array is set at declaration and cannot be changed during program execution.
A slice is a dynamic, resizable segment of an array. It is a structure that contains a pointer to the array, length, and capacity. Slices allow working with subsets of the array and automatically expand when needed.
Main differences:
- Size: array has a fixed size, slice is dynamic.
- Passing: arrays are passed by value (copied), slices by reference (pointer to array).
- Flexibility: slices can be extended using the
appendfunction, arrays cannot.
Example:
var arr [3]int = [3]int{1, 2, 3} // fixed size array
var s []int = arr[0:2] // slice referencing part of the array
s = append(s, 4) // slice expands, and if necessary, a new array is created