1

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

4
  • Do you know the size of SkipField1? Commented Jan 7, 2014 at 19:36
  • Unfortunately No. skipfield1 is a slice of struct of varying size Commented Jan 7, 2014 at 19:55
  • I think you could define a new struct consisting of pointers to the three fixed-length fields in your other struct, and binary.Read would read into that. (Haven't tested and short on time, so not sure enough to submit it as an answer.) Commented Jan 7, 2014 at 20:03
  • Oh, your HeaderBuf thing is nice, ++. Commented Jan 7, 2014 at 20:05

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Could you elaborate a little more on "io.Reader.Read() to manually skip over the skip field portion"
I was suggesting that if you just want to read the fixed header part, then skip the rest of the header, and then read the body, I would recommend using something like func (b *Buffer) Read(p []byte) or func (b *Buffer) ReadBytes(delim byte) to do so. (If you have an io.Reader as your data source then you will have to use Read. The Buffer methods though are more powerful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.