Golang: How to skip struct fields while reading from a buffer?

huangapple go评论95阅读模式
英文:

Golang: How to skip struct fields while reading from a buffer?

问题

以下是翻译好的内容:

type Header struct {
    ByteField1 uint32    // 4字节
    ByteField2 [32]uint8 // 32字节
    ByteField3 [32]uint8 // 32字节
    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)
}

我不想将缓冲区的内容分块读入头部结构体中。我想一次性将字节字段读入,但跳过非字节字段。如果你在给定的链接(http://play.golang.org/p/RQXB-hCq_M)中运行该程序,你会发现binary.Read会抛出一个错误:binary.Read: invalid type []main.SomethingElse

有没有办法可以跳过这个字段?

更新:
根据dommage的回答,我决定将字段嵌入到结构体中,像这样:
http://play.golang.org/p/i0xfmnPx4A

英文:

http://play.golang.org/p/RQXB-hCq_M

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)
}

I don't want to read from the buffer into the header struct in chunks. I want to read into the bytefield in one step but skip non byte fields. If you run the program in the given link (http://play.golang.org/p/RQXB-hCq_M) you will find that binary.Read to throw an error: binary.Read: invalid type []main.SomethingElse

Is there a way that I can skip this field?

Update:
Based on dommage's answer, I decided to embed the fields inside the struct instead like this
http://play.golang.org/p/i0xfmnPx4A

答案1

得分: 1

你可以通过在字段名前加上下划线(_)来跳过某个字段。

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

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

英文:

You can cause a field to be skipped by prefixing it's name with _ (underscore).

But: binary.Read() requires all fields to have a known size. If SkipField1 is of variable or unknown length then you have to leave it out of your struct.

You could then use io.Reader.Read() to manually skip over the skip field portion of your input and then call binary.Read() again.

huangapple
  • 本文由 发表于 2014年1月8日 03:05:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/20979704.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定