I just started yesterday with Go so I apologise in advance for the silly question.
Imagine that I have a byte array such as:
func main(){
arrayOfBytes := [10]byte{1,2,3,4,5,6,7,8,9,10}
}
Now what if I felt like taking the first four bytes of that array and using it as an integer? Or perhaps I have a struct that looks like this:
type eightByteType struct {
a uint32
b uint32
}
Can I easily take the first 8 bytes of my array and turn it into an object of type eightByteType?
I realise these are two different questions but I think they may have similar answers. I've looked through the documentation and haven't seen a good example to achieve this.
Being able to cast a block of bytes to anything is one of the things I really like about C. Hopefully I can still do it in Go.
Look at
encoding/binary
, as well asbytes.Buffer
TL;DR version:
A few things to note here: we pass array[:], alternatively you could declare your array as a slice instead (
[]byte{1, 2, 3, 4, 5}
) and let the compiler worry about sizes, etc, andeightByteType
won't work as is (IIRC) becausebinary.Read
won't touch private fields. This would work: