Sobes.tech
Principal

What is a slice in Go, what does it consist of, and how does it work?

sobes.tech AI

Answer from AI

A slice in Go is a dynamic, resizable, sequential data type that provides a convenient interface for working with arrays.

A slice consists of three components:

  1. Pointer to an array — points to the first element of the array where the slice begins.
  2. Length (len) — the number of elements accessible for reading in the slice.
  3. Capacity (cap) — the maximum number of elements that can fit in the slice starting from the pointer.

A slice works like a window on an array: it does not copy data but only references a part of the array. When adding elements using append, if the capacity is exceeded, a new array is created, data is copied, and the slice starts referencing the new array.

Example:

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

s = append(s, 6) // if cap allows, adds 6 to the original array

Thus, slices are convenient for working with sequences of data without manually managing memory.

What is a slice in Go, what does it consist of, and… - sobes.tech