Println changes capacity of a slice

2020-04-07 04:55发布

Consider the following code

package main

import (
    "fmt"
)

func main() {
    x := []byte("a")
    fmt.Println(x)
    fmt.Println(cap(x) == cap([]byte("a"))) // prints false

    y := []byte("a")
    fmt.Println(cap(y) == cap([]byte("a"))) // prints true

}

https://play.golang.org/p/zv8KQekaxH8

Calling simple Println with a slice variable, changes its capacity. I suspect calling any function with variadic parameters of ...interface{} produces the same effect. Is there any sane explanation for such behavior?

标签: go
1条回答
▲ chillily
2楼-- · 2020-04-07 05:27

The explanation is, like bradfitz point in github, if you don't use make to create a slice, the compiler will use the cap it believes convenient. Creating multiple slices in different versions, or even the same, can result on slices of different capacities.

In short, if you need a concrete capacity, use make([]byte, len, cap). Otherwise you can't trust on a fixed capacity.

查看更多
登录 后发表回答