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?
matt
(Matt Holt)
June 10, 2016, 6:06pm
2
Hi, I formatted your post to use code blocks so it’s more readable.
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.
clbanning
(Charles Banning)
June 10, 2016, 9:57pm
3
calmh
(Jakob Borg)
June 11, 2016, 6:18am
4
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.
@matt , thanks for fixing the formatting
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.
clbanning
(Charles Banning)
June 11, 2016, 8:09pm
8
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
system
(system)
Closed
September 9, 2016, 8:09pm
9
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.