将数组转换为 Go 中的切片

这似乎是一个相当普遍的事情,并在互联网上丰富的例子,但我似乎找不到一个如何将 [32]byte转换为 []byte的例子。

我有一个从外部库调用的函数,它返回一个数组

func Foo() [32]byte {...}

然后,我需要将该结果传递给另一个函数以进行进一步处理。

func Bar(b []byte) { ... }

不幸的是,如果我打电话

d := Foo()
Bar(d)

我明白

cannot convert d (type [32]byte) to type []byte

做什么

[]byte(d)

也好不到哪里去。我如何做到这一点,特别是没有创建数据的副本(当我所做的只是传递数据时,复制这些数据似乎很愚蠢)。

64088 次浏览

This should work:

func Foo() [32]byte {
return [32]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
}


func Bar(b []byte) {
fmt.Println(string(b))
}


func main() {
x := Foo()
Bar(x[:])
}

And it doesn't create a copy of the underlying buffer

This will do the trick:

slice := array[0:len(array)]

Also avoids copying the underlying buffer.

arr[:]  // arr is an array; arr[:] is the slice of all elements

You can generally slice an array by its bounds with : :

var a [32]byte
slice := a[:]

More generally, for the following array :

var my_array [LENGTH]TYPE

You can produce the slice of different sizes by writing :

my_array[START_SLICE:END_SLICE]

Omitting START_SLICE if it equals to the low bound and END_SLICE if equals to the high bound, in your case :

a[0:32]

Produces the slice of the underlying array and is equivalent to :

a[0:]
a[:32]
a[:]