C style struct to data (byte array) mapping, but in Go

So in Go I have this struct:

type msgHeader struct {
	format    byte
	length    [2]byte //BCD-4
	msgType   byte
}

Then I have this byte array and variable:

var data [4]byte{0x46, 0x00, 0x04, 0x45}
var hdr msgHeader

How do I map hdr to data so that I can use i.e hdr.format?
What is the Go way to this?

Hi, I formatted your post to use code blocks so it’s more readable. :slight_smile:

So, you want to do map[msgHeader][4]byte but you can’t because equality on the msgHeader is not defined. Did I read you right?

You could always do map[*msgHeader][4]byte - pointers have equality defined.

or the short form: Go Playground - The Go Programming Language

You can also use the more general Read and Write functions in package encoding/binary. They correctly serialize an entire struct at a time.

On mobile, otherwise I’d have given you an example. :slight_smile:

@matt, thanks for fixing the formatting :slight_smile:

I meant mapping in a different way, not exactly by using a map data structure, I meant mapping to memory

Thanks @clbanning, this might do the trick. Not sure this would be the most efficient way if you have big data structures or many structures, but for now this should work for me.

@calmh,

I had a look at the encoding/binary package and used it like this: https://play.golang.org/p/s9URpqKhhh , however I get a panic which I need to figure out why.

Make the fields accessible by reflect package … https://play.golang.org/p/dTqM8OefLy

(However, the direct initialization of the msgHeader value is more performant, since it doesn’t require reflection.)

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.