Slice length and capacity

Hi,
I’m new to Go and i’ve just read this doc page about slices
Trying some stuff about slice length and capacity in Go Playground, I face the following problem and
I can’t figure out what’s going on :

    // I declare an empty int slice :
    a := []int{}
    fmt.Println("a : ", a)             // a : []
    fmt.Println("length : ", len(a))   // length : 0
    fmt.Println("capacity : ", cap(a)) // capacity : 0
 
    // Ok. Now I add an element to a :

    a = append(a, 1)
    fmt.Println("a : ", a)             // a : [1]
    fmt.Println("length : ", len(a))   // length : 1
    fmt.Println("capacity : ", cap(a)) // capacity : 2 <= ??

    // Hey what ? capacity = length + 1 ?
    // Adding another element and now everything seems ok again :

    a = append(a, 2)
    fmt.Println("a : ", a)             // a : [1, 2]
    fmt.Println("length : ", len(a))   // length : 2
    fmt.Println("capacity : ", cap(a)) // capacity : 2

I’ve tried differents things, like appending first another slice to a, not a single int, but the result is the same : after the first append call, capacity is greater than length. Could you explain me what I miss or misunderstand ?
Thank for your help

https://blog.golang.org/slices (in short: the slice will grow beyond what is needed now to allow for additional growth while minimizing copies)

1 Like

Ok I think I understand, thank you very much !

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.