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