Sobes.tech
Junior — Middle

What will happen to the length and capacity of a slice if you add 10 elements to it when it is initially empty?

sobes.tech AI

Answer from AI

If you have an empty slice in Go (length and capacity are both 0), and you add 10 elements to it using the append function, then:

  • The length of the slice will become 10 — the number of elements you added.
  • The capacity of the slice will be increased automatically, usually with some extra space to avoid frequent memory reallocations. The exact capacity depends on the implementation, but it is often 16 or more to accommodate new elements and have some buffer for future additions.

Example:

var s []int // empty slice
s = append(s, make([]int, 10)...) // adding 10 elements
fmt.Println(len(s)) // 10
fmt.Println(cap(s)) // >=10, usually 16 or 20

Thus, the capacity increases dynamically to efficiently manage memory as the slice grows.

What will happen to the length and capacity of a… - sobes.tech