Sobes.tech
Middle

What is a slice in Go?

sobes.tech AI

Answer from AI

A slice in Go is a dynamic array that represents a reference to a contiguous segment of an array. Unlike fixed-length arrays, slices can change size during runtime.

Main characteristics of a slice:

  • Contains a pointer to the underlying array, along with its length (len) and capacity (cap).
  • Allows working with subsets of an array without copying data.
  • When adding elements using the append function, it may allocate a new array if the current capacity is insufficient.

Example of using a slice:

package main
import "fmt"

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

    s = append(s, 6) // add an element
    fmt.Println(s) // [2 3 4 6]
}

Slices are the primary way to work with sequences in Go; they are convenient and efficient.

What is a slice in Go? — Golang - sobes.tech