2013-09-29 02:22
浏览 1.6k


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?

图片转代码服务由CSDN问答提供 功能建议

我是Go语言的新手,正在尝试编写一个读取RPM文件的应用程序。 每个块的开头都有一个 [4] byte 的Magic char。


  type Lead struct {
 Magic [4] byte 
 Major,Minor byte 
 Type uint16  
 Arch uint16 
 SigType uint16 


  lead:= Lead {} 
lead.Magic = buffer [0:4] 

我正在在线搜索,不确定如何 从切片到数组(不复制)。 我总是可以将Magic设置为 [] byte (甚至是 uint64 ),但是我对如何从 [] byte [4] byte (如果需要)?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

5条回答 默认 最新

  • douyanti2808 2014-01-28 07:45

    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.

    Go Playground

    解决 无用
    打赏 举报

相关推荐 更多相似问题