douqiang5933 2013-09-29 02:22
浏览 2083
已采纳

在Golang中,如何将切片转换为数组

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?

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog