英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论