douxianwu2221 2015-01-18 17:59
浏览 710
已采纳

GoLang:结构中的可变长度数组,用于二进制读取


I'm trying to reimplement a program it did in C a few years ago in Go
The program should read a "record"-like structured binary file and do something with the record (what is done with the records itself is not relevant for this question)

Such a datafile consists of many records where each record has the following definition:

REC_LEN   U2 // length of record after header
REC_TYPE  U1 //a type
REC_SUB   U1 //a subtype
REC_LEN x U1 //"payload" 

My problem now is how to specify that variable length byte[] in a struct in Go?
My plan was to use binary.Read to read the records
Here's what I've tried so far in Go:

type Record struct {
    rec_len uint16
    rec_type uint8
    rec_sub uint8
    data [rec_len]byte
}

Unfortunatelly it seems I can't reference a field of a struct within the same struct as I get the following error:

xxxx.go:15: undefined: rec_len
xxxx.go:15: invalid array bound rec_len

I'd appreciate any ideas pointing me in the right direction
Thanks
KR

  • 写回答

1条回答 默认 最新

  • dongtiaobeng7901 2015-01-18 19:20
    关注

    You can read the record as follows:

    var rec Record
    
    // Slurp up the fixed sized header.
    
    var buf [4]byte
    _, err := io.ReadFull(r, buf[:])
    if err != nil {
        // handle error
    }
    rec.rec_len = binary.BigEndian.Uint16(buf[0:2])
    rec.rec_type = buf[2]
    rec.rec_sub = buf[3]
    
    // Create the variable part and read it.
    
    rec.data = make([]byte, rec.rec_len)
    _, err = io.ReadFull(r, rec.data)
    if err != nil {
        // handle error
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥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,如何解決?