Sobes.tech
Junior — Middle

Explain the mechanism of slices in the Go programming language.

sobes.tech AI

Answer from AI

Slices in Go are dynamic, mutable views of sequences of elements of the same type. They are based on arrays but provide a more convenient and flexible interface for working with sequences.

A slice consists of three components:

  • a pointer to the first element of the array that is included in the slice,
  • length (len) — the number of elements in the slice,
  • capacity (cap) — the maximum number of elements that can be contained, starting from the pointer.

When creating a slice from an array or another slice, a new slice is created that references the same underlying array. Changes through the slice are reflected in the array and other slices referencing the same segment.

Example:

arr := [5]int{1, 2, 3, 4, 5}
s := arr[1:4] // slice of elements with indices 1,2,3
fmt.Println(s) // [2 3 4]

s[0] = 20
fmt.Println(arr) // [1 20 3 4 5]

If adding elements with append causes the slice to exceed its capacity, a new array is created, and data is copied there, allowing the slice to expand dynamically.

Thus, slices are a convenient way to work with sequences without manually managing arrays and their sizes.

Explain the mechanism of slices in the Go programming… - sobes.tech