为什么我不能将一个新分配的字节数组赋值给一个类型为 []byte 的变量?

huangapple go评论96阅读模式
英文:

why cannot I assign a newly allocated byte array to a variable with []byte as type?

问题

我正在尝试声明一个未指定大小的[]byte类型的数组变量,并将其填充为大小为256的分配数组,代码如下:

var buf []byte
buf = new([256]byte)

不幸的是,它不起作用。返回的编译错误如下:

无法将*new([256]byte)(类型为[256]byte)分配给类型[]byte

有什么想法吗?

英文:

I am trying to declare a variable of type array with unspecified size []byte and then filling it with an allocated array of size 256 as follows:

var buf []byte
buf = new([256]byte)

Unfortunately, it does not work. The compile error returned is the following:

cannot use *new([256]byte) (type [256]byte) as type []byte in assignment

Any idea?

答案1

得分: 6

你想将一个数组分配给一个切片,这是行不通的(参见《Go切片:用法和内部原理》)。

要创建一个切片,可以使用以下代码:

var buf []byte
buf = make([]byte, 256)

两者的区别是:

  • 数组变量表示整个数组;它不是指向第一个数组元素的指针(与C语言中的情况不同)。
    这意味着当你赋值或传递一个数组值时,会复制其内容。(为了避免复制,你可以传递一个指向数组的指针,但那就是指向数组的指针,而不是数组本身。)
    可以将数组视为一种类似于结构体的东西,但其字段是按索引而不是按名称进行访问的:一个固定大小的复合值。

相比之下:

  • 切片是对数组片段的描述。
    它由指向数组的指针、片段的长度和其容量(片段的最大长度)组成。

如果你想创建一个数组并将其分配给一个数组,可以使用以下代码:

var buf [256]byte
buf = [256]byte{}
英文:

You want to assign an array to a slice, which won't work (see "Go Slices: usage and internals")

To make a slice instead, use:

var buf []byte
buf = make([]byte, 256)

The difference:

> An array variable denotes the entire array; it is not a pointer to the first array element (as would be the case in C).
This means that when you assign or pass around an array value you will make a copy of its contents. (To avoid the copy you could pass a pointer to the array, but then that's a pointer to an array, not an array.)
One way to think about arrays is as a sort of struct but with indexed rather than named fields: a fixed-size composite value.

Versus:

> A slice is a descriptor of an array segment.
It consists of a pointer to the array, the length of the segment, and its capacity (the maximum length of the segment).


If you want to create an array (an assign it to an array), that would have been:

var buf [256]byte
buf = [256]byte{}

答案2

得分: 2

你还可以通过像这样对其进行切片,将新分配的数组用作切片:

var slice []byte = buf[:]

这将创建一个由数组buf支持的切片slice。

英文:

You can also use the newly allocated array as a slice by slicing it like this:

var slice []byte = buf[:]

This creates slice as a slice that is backed by the array buf.

huangapple
  • 本文由 发表于 2014年5月10日 17:02:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/23579122.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定