douxianwu2221
douxianwu2221
2015-01-18 17:59

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

  • struct
已采纳


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 dongtiaobeng7901 6年前

    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
    }
    
    点赞 评论 复制链接分享