Sobes.tech
Junior — Middle

Mis on andmestruktuuri slice peamine funktsioon programmeerimiskeeltes?

sobes.tech AI

Vastus AI-lt

In programming languages, for example in Go, a slice is a dynamic array that allows working with a sequence of elements of variable length.

Main functions of a slice:

  • Provide a convenient interface for working with subsets of arrays.
  • Allow changing the size of the sequence during execution.
  • Contain a pointer to the base array, length, and capacity.

Example in Go:

numbers := []int{1, 2, 3, 4, 5} // slice of 5 elements
subSlice := numbers[1:4]          // slice with elements 2,3,4
subSlice = append(subSlice, 6)    // add an element, the slice expands

Thus, slices are useful for flexible work with arrays without the need to know the size in advance.