Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang:如何在从缓冲区读取时跳过结构字段?_Go_Buffer - Fatal编程技术网

Golang:如何在从缓冲区读取时跳过结构字段?

Golang:如何在从缓冲区读取时跳过结构字段?,go,buffer,Go,Buffer,我不想从缓冲区中分块读取头结构。我想一步读入bytefield,但跳过非字节字段。如果在给定的链接()中运行程序,您将发现binary.Read抛出错误:binary.Read:invalid type[]main.SomethingElse 有没有办法跳过这个字段 更新: 根据dommage的回答,我决定像这样将字段嵌入结构中 您可以通过在字段名称前加上u(下划线)来跳过该字段 但是:binary.Read()要求所有字段都具有已知大小。如果SkipField1的长度可变或未知,则必须将其从结

我不想从缓冲区中分块读取头结构。我想一步读入bytefield,但跳过非字节字段。如果在给定的链接()中运行程序,您将发现binary.Read抛出错误:binary.Read:invalid type[]main.SomethingElse

有没有办法跳过这个字段

更新: 根据dommage的回答,我决定像这样将字段嵌入结构中

您可以通过在字段名称前加上u(下划线)来跳过该字段

但是
binary.Read()
要求所有字段都具有已知大小。如果
SkipField1
的长度可变或未知,则必须将其从结构中删除


然后可以使用
io.Reader.Read()
手动跳过输入的跳过字段部分,然后调用
binary.Read()
再次。

你知道
SkipField1
的大小吗?不幸的是,不知道。SkipField1是一个大小不同的结构片。我想你可以定义一个新的结构,它由指向另一个结构中三个固定长度字段的指针和
二进制组成。Read
会读入其中。(没有测试,时间很短,所以不确定是否可以作为答案提交。)哦,你的HeaderBuf很好,++。你能详细介绍一下“io.Reader.Read()手动跳过跳过字段部分”吗?我的建议是,如果你只想读固定的标题部分,那么跳过标题的其余部分,然后读正文,我建议使用
func(b*Buffer)Read(p[]byte)
func(b*Buffer)ReadBytes(delim byte)
这样做。(如果您有
io.Reader
作为数据源,则必须使用
Read
Buffer
方法更强大。
type Header struct {
    ByteField1 uint32    // 4 bytes
    ByteField2 [32]uint8 // 32 bytes
    ByteField3 [32]uint8 // 32 bytes
    SkipField1 []SomethingElse
}

func main() {
    var header Header
    headerBytes := make([]byte, 68)  // 4 + 32 + 32 == 68
    headerBuf := bytes.NewBuffer(headerBytes)
    err := binary.Read(headerBuf, binary.LittleEndian, &header)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(header)
}