user10133356
user10133356

Reputation:

Capacity of a slice

I am new to Golang and I am following the Tour. The code below produces the following results:

a len=5 cap=5 [0 0 0 0 0]

b len=0 cap=5 []

c len=2 cap=5 [0 0]

d len=3 cap=3 [0 0 0]

How can c have the same cap as b when it was not specified at all?

package main

import "fmt"

func main() {
    a := make([]int, 5)
    printSlice("a", a)

    b := make([]int, 0, 5)
    printSlice("b", b)

    c := b[:2]
    printSlice("c", c)

    d := c[2:5]
    printSlice("d", d)
}

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

Upvotes: 3

Views: 55

Answers (1)

mbuechmann
mbuechmann

Reputation: 5750

Every slice is a pointer type that points to an underlying array. When you make b you create an underlying array to which b points. When you create c by resclicing b you will create a new slice that points to the same underlying array as b.

When you change some entries in b, you will notice that those values get changed in c, too.

There is an official blog entry, that explains all of this in detail: https://blog.golang.org/go-slices-usage-and-internals

Upvotes: 3

Related Questions