Sobes.tech
Junior — Middle

Explain what slices are in Python programming.

sobes.tech AI

Answer from AI

In the Go (Golang) language, slices are dynamic data structures that act as wrappers over arrays. They allow working with sequences of elements of variable length.

Main features of slices:

  • A slice contains a pointer to an array, a length, and a capacity.
  • Length is the number of elements available in the slice.
  • Capacity is the maximum number of elements the slice can hold without reallocating.
  • You can create slices from arrays or other slices using the syntax array[start:end].
  • When adding elements using the append function, a new array with increased capacity is allocated if necessary.

Example:

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
fmt.Println(slice) // [2 3 4 6]

Thus, slices are convenient for working with dynamic sequences without the need to manually manage arrays.