#Question about Slices

6 messages · Page 1 of 1 (latest)

heady wagon
#

Consider the following code:

func main() {
    s := []int{2, 3, 5, 7, 11, 13}
    printSlice(s)

    // Slice the slice to give it zero length.
    s = s[:0]
    printSlice(s)

    // Extend its length.
    s = append(s, 99)
    s = s[:4]
    printSlice(s)

    // Drop its first two values.
        s = s[:6]
    printSlice(s)
}

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

This has the following output:

len=6 cap=6 [2 3 5 7 11 13]
len=0 cap=6 []
len=4 cap=6 [99 3 5 7]
len=6 cap=6 [99 3 5 7 11 13]

My question is, why do we see [99 3 5 7]. Where does the 2 go?

proven lake
#

it's overwritten by append

#

append first try to reuse unused capacity.
Because 6-0 is bigger than 1, it wont make a new slice

heady wagon
#

is append the recommended option to push things into a slice? I'm used to using vectors in c++, so was wondering whats the corresponding function in Go

proven lake
#

yes

#

slices aren't really like vectors, there is no concept of ownership and you can fuck it up