在 Go 中将固定大小的数组转换为可变大小的数组

Convert fixed size array to variable sized array in Go

我正在尝试将固定大小的数组 [32]byte 转换为可变大小的数组(切片)[]byte:

package main

import (
        "fmt"
)

func main() {
        var a [32]byte
        b := []byte(a)
        fmt.Println(" %x", b)
}

但编译器抛出错误:

./test.go:9: cannot convert a (type [32]byte) to type []byte

如何转换?

Go 中没有可变大小的数组,只有切片。如果你想得到整个数组的一部分,这样做:

b := a[:] // Same as b := a[0:len(a)]

使用b := a[:] 获取数组上的切片。另请参阅 this 博客 post 了解有关数组和切片的更多信息。