在Golang中,你如何将切片转换为数组 [英] In Golang how do you convert a slice into an array
问题描述
我是Go的新手,试图编写一个读取RPM文件的应用程序。每个块的开始都有一个魔术字符 [4] byte
。
这是我的结构
类型Lead struct {
Magic [4]字节
主要,次要字节
类型uint16
Arch uint16
名称字符串
OS uint16
SigType uint16
}
我正在尝试以下操作:
lead:= Lead {}
lead.Magic = buffer [0:4]
我在线搜索并不确定如何从切片转到数组(不进行复制)。我总是可以制作魔术 []字节
(甚至 uint64
),但我更加好奇我会如何如果需要,从 [] byte
到 [4] byte
>类型转到$
内置方法 copy 只会将切片复制到切片而非数组切片。
您必须欺骗 copy 来认为数组是分片的
复制(varLead.Magic [:],someSlice [0:4])
或者使用for循环复制:
索引,b:=范围someSlice {
varLead.Magic [ index] = b
}
或者像zupa所做的那样使用文字。我已添加到他们的工作示例中。
I am new to Go and trying to write an application that reads RPM files. The start of each block has a Magic char of [4]byte
.
Here is my struct
type Lead struct {
Magic [4]byte
Major, Minor byte
Type uint16
Arch uint16
Name string
OS uint16
SigType uint16
}
I am trying to do the following:
lead := Lead{}
lead.Magic = buffer[0:4]
I am searching online and not sure how to go from a slice to an array (without copying). I can always make the Magic []byte
(or even uint64
), but I was more curious on how would I go from type []byte
to [4]byte
if needed to?
The built in method copy will only copy a slice to a slice NOT a slice to an array.
You must trick copy into thinking the array is a slice
copy(varLead.Magic[:], someSlice[0:4])
Or use a for loop to do the copy:
for index, b := range someSlice {
varLead.Magic[index] = b
}
Or do as zupa has done using literals. I have added onto their working example.
这篇关于在Golang中,你如何将切片转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!