gpt4 book ai didi

struct - 高语 : Variable length array in struct for use with binary read

转载 作者:IT王子 更新时间:2023-10-29 01:42:54 26 4
gpt4 key购买 nike


我正在尝试用 Go 重新实现它几年前用 C 编写的程序
程序应该读取类似“记录”的结构化二进制文件并对记录做一些事情(对记录本身做了什么与这个问题无关)

这样的数据文件由许多记录组成,其中每个记录都有以下定义:

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

我现在的问题是如何在 Go 的结构中指定可变长度 byte[]?
我的计划是使用 binary.Read 读取记录
到目前为止,这是我在 Go 中尝试过的内容:

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

不幸的是,我似乎无法在同一结构中引用结构的字段,因为我收到以下错误:

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

如果有任何想法能指引我正确的方向,我将不胜感激
谢谢
韩国

最佳答案

您可以阅读记录如下:

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
}

关于struct - 高语 : Variable length array in struct for use with binary read,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28012952/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com