gomakefilecapacity

How capacity value is changing based on value assignment type?


package main

import "fmt"

func main() {
    mySlice := make([]int, 2, 4)
    mySlice = []int{1, 2, 3, 4, 5}  `when i assign value like this, both length and cap are 5,5`    
        /*mySlice[0] = 1
    mySlice[1] = 2
    mySlice = append(mySlice, 3, 4, 5)*/ `when i assign value like this, len is 5, but cap is 8`
    fmt.Println("len", len(mySlice), cap(mySlice))
}

How capacity value is varying based on value assigned type. How internally it is working??


Solution

  • A slice literal has its capacity equal to its length.

    When you append to a slice that is full to its capacity, a new array is allocated that is larger than the array of the original slice. The capacity of the new array is determined by the runtime, and it depends on the implementation. It is usually a constant times the original capacity, so repetitive additions to a slice do not cause a new allocation for every append, keeping the amortized complexity of append constant time.