Println changes capacity of a slice

后端 未结 1 1242
长发绾君心
长发绾君心 2021-01-19 00:16

Consider the following code

package main

import (
    \"fmt\"
)

func main() {
    x := []byte(\"a\")
    fmt.Println(x)
    fmt.Println(cap(x) == cap([]byt         


        
相关标签:
1条回答
  • 2021-01-19 00:38

    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.

    0 讨论(0)
提交回复
热议问题