Sobes.tech
Junior — Middle

How do concepts of length and capacity of a slice differ in programming language?

sobes.tech AI

Answer from AI

In Go language, a slice (slice) has two important parameters: length (len) and capacity (cap).

  • Length (len) — the number of elements that the slice currently contains and can access.
  • Capacity (cap) — the maximum number of elements the slice can hold without allocating new memory.

For example:

arr := [5]int{1, 2, 3, 4, 5}
s := arr[1:3] // the slice contains elements 2 and 3
fmt.Println(len(s)) // 2
fmt.Println(cap(s)) // 4, because the slice starts from arr[1], and from there to the end of the array are 4 elements

Capacity is important for understanding when adding elements to a slice will cause a reallocation of memory.

How do concepts of length and capacity of a slice… - sobes.tech