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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况