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))
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.
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)
}