Why the capacity of the slice greater than expected


(Sandeep Gaur) #1

For the code mentioned bewlow:
package main
import ( “fmt”)
func main() {
a := []int{12} // … makes the compiler determine the length
fmt.Println(len(a))
fmt.Println(cap(a))

a=append(a,112)

fmt.Println(a)	
fmt.Println(len(a))
fmt.Println(cap(a))

a=append(a,234)

fmt.Println(a)
fmt.Println(len(a))
fmt.Println(cap(a))}

OutPut:
1
1
[12 112]
2
2
[12 112 234]
3
4

Can you anyone please explain why in last line of the output it is 4 why not 3 ?


(Ali Koyuncu) #2

this magic comes from append function, when append function realize that it can’t store more than the current slice capacity, it creates new slice with double capacity.


(Gonzalo Sayago) #3

Check this topic

https://forum.golangbridge.org/t/slice-append-what-is-the-actual-resize-factor