# Why the capacity of the slice greater than expected

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 ?

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.

1 Like
1 Like
``````package main

import "fmt"

func main() {
var s []int
printSlice(s)

// append works on nil slices.
s = append(s, 0)
printSlice(s)

// The slice grows as needed.
s = append(s, 1)
printSlice(s)

// We can add more than one element at a time.
s = append(s, 2)
printSlice(s)

// We can add more than one element at a time.
s = append(s, 3)
printSlice(s)

// We can add more than one element at a time.
s = append(s, 5, 6, 7, 8, 9)
printSlice(s)
}

func printSlice(s []int) {
fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}
``````

## OUTPUT:

len=0 cap=0 []
len=1 cap=1 
len=2 cap=2 [0 1]
len=3 cap=4 [0 1 2]
len=4 cap=4 [0 1 2 3]
len=9 cap=10 [0 1 2 3 5 6 7 8 9]

If it doubles why the capacity at last is 10, why not 16? Any idea?