将字节数组切片以符合Golang中参数的结构体?

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

Slicing a byte array to conform to a struct for param in Golang?

问题

我大致有这样的代码:

type Guid [16]byte

type Payload struct {
	....
	SthGuid  [17]byte
}

func (h *...) Get(guid Guid) (... error) {

}

我想要使用SthGuid的最后16个字节来调用Get方法,例如:

Get(PayloadInstance.SthGuid[1:16]))

无法将SthGuid[1:16](类型为[]byte的值)转换为Guid类型

我尝试使用SthGuid[1:]来切片第一个字节,并将最后16个字节作为输入参数,但这种方式不起作用。

英文:

I have something roughly like this

type Guid [16]byte

type Payload struct {
	....
	SthGuid  [17]byte
}


func (h *...) Get(guid Guid) (... error) {

}

and I want to call Get with the last 16 bytes of SthGuid. E.g.,

Get(PayloadInstance.SthGuid[1:16]))

cannot convert SthGuid[1:16] (value of type []byte) to Guid

I'm trying to call SthGuid[1:] to slice the first byte and use the last 16 bytes as an input param. Doesn't work that way.

答案1

得分: 1

你可以使用正确的类型进行数组复制,例如:

var guid [16]byte
copy(guid[:], SthGuid[1:16])
Get(guid)

或者,从 Go 1.17 开始,你可以尝试使用切片到数组的转换:

https://tip.golang.org/ref/spec#Conversions_from_slice_to_array_pointer

英文:

You can do copying of array with right type, e.g:

var guid [16]byte
copy(guid[:], SthGuid[1:16])
Get(guid)

or, as a Go 1.17 you can try to use slice to array conversion:

https://tip.golang.org/ref/spec#Conversions_from_slice_to_array_pointer

huangapple
  • 本文由 发表于 2022年1月28日 07:16:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/70887026.html
匿名

发表评论

匿名网友

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

确定