英文:
Is there a way to convert a bytes slice to a custom type of a byte array
问题
你好!根据你的要求,我将为你翻译以下内容:
假设我有如下代码:
type SomeType [16]byte
func foo(bar []byte) {
...
}
在 foo()
函数中,如何将 bar
复制到一个 SomeType
实例中?
英文:
Say I have a some code like this:
type SomeType [16]byte
func foo(bar []byte) {
...
}
How can I copy bar
in foo()
to a SomeType
instance?
答案1
得分: 3
从Go 1.17开始,你可以将切片转换为数组指针,前提是切片的大小至少足以填充声明的数组。只有当你期望bar至少为16个字节时,这才能满足你的需求。
package main
import "fmt"
type SomeType [16]byte
func foo(bar []byte) SomeType {
return *(*SomeType)(bar)
}
func main() {
fmt.Println(foo([]byte("A 16 byte slice!"))) // 可行
fmt.Println(foo([]byte("A 16 byte slice and then some more"))) // 可行,但你只能访问前16个字节
fmt.Println(foo([]byte("too short"))) // 会引发恐慌,因为底层数组太短
}
英文:
As of Go 1.17 you can convert a slice to an array pointer so long as the slice is at least large enough to fill the declared array. This would only meet your needs if you expect bar to be at least 16 bytes.
package main
import "fmt"
type SomeType [16]byte
func foo(bar []byte) SomeType {
return *(*SomeType)(bar)
}
func main() {
fmt.Println(foo([]byte("A 16 byte slice!"))) // works
fmt.Println(foo([]byte("A 16 byte slice and then some more"))) // works but you only access the first 16 bytes
fmt.Println(foo([]byte("too short"))) // panics because the underlying array is too short
}
答案2
得分: 2
使用copy
函数,但首先将数组转换为切片:
type SomeType [16]byte
func foo(bar []byte) SomeType {
var ret SomeType
copy(ret[:], bar)
return ret
}
func main() {
r := foo([]byte{1, 2, 3})
fmt.Println(r)
}
英文:
Use copy
, but convert the array to a slice first:
type SomeType [16]byte
func foo(bar []byte) SomeType {
var ret SomeType
copy(ret[:], bar)
return ret
}
func main() {
r := foo([]byte{1, 2, 3})
fmt.Println(r)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论