2

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.

fredmaggiowski
  • 2,232
  • 3
  • 25
  • 44
Tim Merrifield
  • 6,088
  • 5
  • 31
  • 33
  • Does this https://stackoverflow.com/a/53429894/12817546 and this https://play.golang.org/p/IYpv3YJsZO5 answer your question in part? –  Sep 19 '20 at 09:46

1 Answers1

3

Look at encoding/binary, as well as bytes.Buffer

TL;DR version:

import (
    "encoding/binary"
    "bytes"
)

func main() {
    var s eightByteType
    binary.Read(bytes.NewBuffer(array[:]), binary.LittleEndian, &s)
}

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, and eightByteType won't work as is (IIRC) because binary.Read won't touch private fields. This would work:

type eightByteType struct {
    A, B uint32
}
cthom06
  • 9,389
  • 4
  • 36
  • 28
  • Does this code actually copy data from the array to the struct? – mkm May 26 '11 at 15:12
  • @ithkuil what do you mean? Actually copy as opposed to what? – cthom06 May 27 '11 at 11:43
  • as opposed to what you can do in C, cast a bytearray to a struct, so that the struct uses the same memory region occupied by the bytearray without copying. This was my interpretation of the last part of the question: "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." – mkm May 27 '11 at 13:33
  • @ithkuil in that case you need to use package `unsafe` – cthom06 May 27 '11 at 13:50