Sobes.tech
Senior

What is a slice in Go?

sobes.tech AI

Answer from AI

A slice in Go is a dynamic, flexible, and convenient way to work with sequences of elements of the same type. It is a reference to a part of an array with a specified length and capacity.

Main characteristics of a slice:

  • A slice contains a pointer to the underlying array, a length (len), and a capacity (cap).
  • Length is the number of elements accessible in the slice.
  • Capacity is the maximum number of elements that can be stored, starting from the current pointer.
  • Slices can be extended using the append function, which creates a new array if necessary.

Example of creating and using a slice:

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

s = append(s, 6)                 // add an element, possibly creating a new array
fmt.Println(s)                   // [2 3 4 6]

Slices allow efficient work with sequences without copying data, managing only references and metadata.