有没有一种方法可以将字节切片转换为自定义类型的字节数组?

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

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)
}

huangapple
  • 本文由 发表于 2021年12月9日 01:44:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/70279467.html
匿名

发表评论

匿名网友

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

确定