Arrays 将Go中的固定大小数组转换为可变大小数组
我正在尝试将固定大小的数组Arrays 将Go中的固定大小数组转换为可变大小数组,arrays,go,type-conversion,Arrays,Go,Type Conversion,我正在尝试将固定大小的数组[32]字节转换为可变大小的数组(切片)[]字节: 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 我应该如何
[32]字节
转换为可变大小的数组(切片)[]字节
:
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[:]
在现有阵列上获取切片。有关数组和切片的更多信息,请参阅博客文章。注意,切片的行为有点像可变大小的数组,如果在切片上继续使用append
,它将在必要时通过重新分配而增长。