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

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

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.Printf("%x\n", b)
}

但是编译器报错:

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

我应该如何进行转换?

英文:

I'm trying to convert a fixed size array [32]byte to variable sized array (slice) []byte:

package main

import (
        "fmt"
)

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

but the compiler throws the error:

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

How should I convert it?

答案1

得分: 39

使用b := a[:]来获取你所拥有的数组的切片。还可以参考这篇博文,了解更多关于数组和切片的信息。

英文:

Use b := a[:] to get the slice over the array you have. Also see this blog post for more information about arrays and slices.

答案2

得分: 19

在Go语言中,没有可变大小的数组,只有切片(slices)。如果你想要获取整个数组的切片,可以这样做:

b := a[:] // 等同于 b := a[0:len(a)]
英文:

There are no variable-sized arrays in Go, only slices. If you want to get a slice of the whole array, do this:

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

huangapple
  • 本文由 发表于 2015年1月20日 21:48:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/28046949.html
匿名

发表评论

匿名网友

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

确定