Junior — Middle
Kas saaksite selgitada, mis on lõik (slice) programmeerimises ja kuidas see töötab?
sobes.tech AI
Vastus AI-lt
In Go, a slice is a dynamic, resizable fragment of an array. It is a structure that contains:
- a pointer to the first element of the array,
- the length (number of elements in the slice),
- the capacity (the maximum number of elements the slice can hold without reallocation).
Slices allow working with sequences of elements without copying data.
Example of creating and using a slice:
arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // slice of elements with indices 1,2,3
fmt.Println(slice) // [2 3 4]
slice = append(slice, 6) // add an element, if necessary, new memory is allocated
fmt.Println(slice) // [2 3 4 6]
Slices are useful because they can be created from existing slices, their size can be changed, and they can be passed to functions without copying the entire array.