Question

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?

Was it helpful?

Solution

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{}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top