本文介绍了Println更改切片的容量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码

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

使用slice变量调用简单的Println会更改其容量.我怀疑调用可变参数...interface{}的任何函数都会产生相同的效果.对于这种行为是否有任何理智的解释?

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?

推荐答案

解释与 github ,如果您不使用make创建切片,则编译器将使用它认为方便的上限. 创建不同版本甚至相同版本的多个片可能会导致容量不同的片.

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.

简而言之,如果您需要具体的功能,请使用make([]byte, len, cap).否则,您将无法信任固定的容量.

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

这篇关于Println更改切片的容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 04:42