如何将切片转换为数组? [英] How do you convert a slice into an array?
问题描述
我正在尝试编写一个读取RPM文件的应用程序.每个块的开头都有一个 [4] byte
的Magic char.
I am trying to write an application that reads RPM files. The start of each block has a Magic char of [4]byte
.
这是我的结构
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]
我正在在线搜索,不确定如何从切片到数组(不进行复制).我总是可以将Magic设置为 [] byte
(甚至是 uint64
),但是我对如何从 [] byte
到 [4] byte
(如果需要)?
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?
推荐答案
内置方法 copy 只会将切片复制到切片,而不是将切片复制到数组.
The built in method copy will only copy a slice to a slice NOT a slice to an array.
您必须欺骗 copy 认为数组是一个切片
You must trick copy into thinking the array is a slice
copy(varLead.Magic[:], someSlice[0:4])
或使用for循环进行复制:
Or use a for loop to do the copy:
for index, b := range someSlice {
varLead.Magic[index] = b
}
或者像zupa使用文字所做的那样做.我已经添加到他们的工作示例中.
Or do as zupa has done using literals. I have added onto their working example.
这篇关于如何将切片转换为数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!