Sobes.tech
Senior

What is a slice in Go, what does it consist of, and what is it used for?

sobes.tech AI

Answer from AI

A slice in Go is a dynamic, resizable, sequential data type that represents a window (slice) on an array. It consists of three components:

  • A pointer to the first element of the array underlying the slice.
  • Length (len) — the number of elements accessible through the slice.
  • Capacity (cap) — the maximum number of elements that can be contained, starting from the pointer, without allocating new memory.

Slices are used for convenient handling of data sequences, allowing dynamic resizing, passing parts of arrays without copying, and efficient memory management.

Example of creating and using a slice:

arr := [5]int{1, 2, 3, 4, 5}
slice := arr[1:4] // slice of elements 2,3,4
fmt.Println(slice) // [2 3 4]
slice = append(slice, 6) // add an element, possibly allocating new memory
fmt.Println(slice) // [2 3 4 6]