Junior — Middle
Mis juhtub viiluga pikkuse ja mahutavusega, kui sinna lisada 10 elementi, kui see algselt on tühi?
sobes.tech AI
Vastus AI-lt
If you have an empty slice in Go (length and capacity are 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 will often be 16 or more, to accommodate new elements and have some spare capacity for future additions.
Example:
var s []int // empty slice
s = append(s, make([]int, 10)...) // add 10 elements
fmt.Println(len(s)) // 10
fmt.Println(cap(s)) // >=10, usually 16 or 20
This way, the capacity increases dynamically to efficiently manage memory as the slice grows.