Println更改切片的容量 [英] Println changes capacity of a slice

查看:49
本文介绍了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?

推荐答案

解释与

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更改切片的容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆