According to http://golang.org/pkg/encoding/binary/#Read :

Data must be a pointer to a fixed-size value or a slice of fixed-size values.

So you can't use slice []byte in your structure. But you can use fixed size array for it.
Like this:

package main

import (
    "bytes"
    "encoding/binary"
    "fmt"
)

type T struct {
    A int16
    B int8
    C [256]byte
}

func main() {
    // Create a struct and write it.
    t := T{A: 99, B: 10}
    buf := &bytes.Buffer{}
        
    err := binary.Write(buf, binary.BigEndian, t)
    
    if err != nil {
        panic(err)
    }
    fmt.Println(buf)

    // Read into an empty struct.
    t = T{}
    err = binary.Read(buf, binary.BigEndian, &t)
    if err != nil {
        panic(err)
    }
    fmt.Printf("%d %d", t.A, t.B)
}

Go playground

Answer from RoninDev on Stack Overflow
🌐
Reddit
reddit.com › r/golang › the *right* way to do a bytesstruct in golang
r/golang on Reddit: The *right* way to do a bytes<->struct in Golang
October 10, 2024 -

In C, for a protocol stack, I'd have a byte array from the network. I'd inspect a couple of bytes to determine what the packet is supposed to be at least, and then cast it to the appropriate struct. Something like this:

bptr = <malloc'd buffer>
*protocolStruct = *(ProtocolObject)bptr

In golang, do I use the binary package, the unsafe { }, or what?

Let''s assume I have a struct for an ARP request, something like:

type NativeAddress struct
      AddressType uint32
      Address [16]byte
}

And my ARP request structure is

type ARPRequest struct {
     SAP uint16
     NSAP uint16
     SrcAddress NativeAddres
     DstAddress NativeAddress
     RequestedAddress uint64
}

How does this get encoded with something like Gob and how does it get received on the other end? Wasteful though it is, everything is aligned. Can I just assume it gets encoded linearly ion the wire? In ancient C, I could do a tagged union that worked the same way, but modern C doesn't do that, you really can't count on what two C compilers will generate for structs <-> bytes. Or am I making this harder than it has to be -- should I just encode everything, every packet in protobuf, avro etc? In JVM langues, I have the same problem so I was hoping Golang handled it better. Even with Gob, can two architectures using Golang encode and decode structs reliably and, I still have the problem, after I read the SAP and NSAP bytes, only then do I know what struct it actually is and thus, I can "cast" it, or does Gob take care of that? I can't use something like JSON encoding, this is binary date.

I'd love to just have something that read bytes and said "I just received struct X" or "I have no idea what I just got" if I can't do the C style tricks.

🌐
Go
go.dev › play › p › vUUboD7O_T
Go Playground - The Go Programming Language
Common problems companies solve with Go · Stories about how and why companies use Go
🌐
Google Groups
groups.google.com › g › golang-nuts › c › nEGhrzwj94I
Casting []byte to data struct
You can't, mainly because it breaks the type system (what if one of the struct fields were a pointer?) but also because it produces non-portable code. http://golang.org/pkg/encoding/binary/ will read binary data into a struct as long as you tell it the endianness and the struct uses only basic ...
🌐
Reddit
reddit.com › r/golang › trying to convert byte array into a struct.
r/golang on Reddit: Trying to convert byte array into a struct.
September 8, 2024 -

So apparently im parsing a byte array which represent flags in macho file

How I can parse this into a struct.

type Flags struct {
noundefs                      bool
incrlink                      bool
dyldlink                      bool
bindatload                    bool
prebound                      bool
split_segs                    bool
lazy_init                     bool
twolevel                      bool
force_flat                    bool
nomultidefs                   bool
nofixprebindin                bool
prebindable                   bool
allmodsbound                  bool
subsections_via_symbols       bool
canonical                     bool
weak_defines                  bool
binds_to_weak                 bool
allow_stack_execution         bool
root_safe                     bool
setuid_safe                   bool
no_reexported_dylibs          bool
pie                           bool
dead_strippable_dylib         bool
has_tlv_descriptors           bool
no_heap_execution             bool
app_extension_safe            bool
nlist_outofsync_with_dyldinfo bool
sim_support                   bool
dylib_in_cache                bool
}


func ParseIntoFlag(p *parser.Parser, data chan any) chan any {
   buf := bytes.NewBuffer(p.Data[0:4])
   fmt.Println(binary.LittleEndian.Uint32(p.Data[0:4]))
   p.Data = p.Data[4:]
   flags := Flags{}
   binary.Read(buf, binary.LittleEndian, flags)
    data <- flags
    return data
}

FYI: im new to golang and code may be not the best.

🌐
Blogger
self-learning-java-tutorial.blogspot.com › 2019 › 05 › go-json-unmarshal-byte-array-to-struct.html
Programming for beginners: Go: json: Unmarshal byte array to struct
May 15, 2019 - Step 2: Define an Employee variable and unmarshal the byte array to employee variable. ... Find the below working application. ... package main import ( "encoding/json" "fmt" ) //Employee represent an employee object type Employee struct { FirstName string LastName string ID int } func (emp *Employee) aboutMe() { fmt.Println("FirstName : ", emp.FirstName) fmt.Println("LastName : ", emp.LastName) fmt.Println("ID : ", emp.ID) } func main() { //Step 1: Define byte array byteArray := []byte{123, 34, 70, 105, 114, 115, 116, 78, 97, 109, 101, 34, 58, 34, 75, 114, 105, 115, 104, 110, 97, 34, 44, 34,
🌐
GitHub
gist.github.com › festime › aaebdc4ea7386bf78d88bdaebfa2d669
Unmarshal a slice of bytes to a struct whose fields are also some structs. Custom type needs to implement json.Unmarshaler interface. · GitHub
Unmarshal a slice of bytes to a struct whose fields are also some structs. Custom type needs to implement json.Unmarshaler interface. - unmarshal-bytes-to-struct-example.go
🌐
Go Forum
forum.golangbridge.org › technical discussion
C style struct to data (byte array) mapping, but in Go - Technical Discussion - Go Forum
June 10, 2016 - 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 msgHeade…
Find elsewhere
🌐
Reddit
reddit.com › r/golang › convert a byte slice to struct
r/golang on Reddit: Convert a byte slice to struct
April 29, 2022 -

Hi. I figured out how to convert a Go struct right into byte slice without reflection or memory allocations:

package main

import (
	"fmt"
	"unsafe"
)

type Movement struct {
	Opcode int
	X      float64
	Y      float64
	Z      float64
}

const (
	movementSize = int(unsafe.Sizeof(Movement{}))
)

func main() {
	mv := Movement{
		Opcode: 32,
		X:      13.34,
		Y:      20.36,
		Z:      45.13,
	}
	packet := (*[movementSize]byte)(unsafe.Pointer(&mv))[:]

	fmt.Println(mv)
	fmt.Println(len(packet))
	fmt.Println(packet)
}

The output is:

{32 13.34 20.36 45.13}
32
[32 0 0 0 0 0 0 0 174 71 225 122 20 174 42 64 92 143 194 245 40 92 52 64 113 61 10 215 163 144 70 64]

Now I would like to know how to convert a byte slice into struct in a similar manner. Yes, I know about the binary package, but that's not what I need.

🌐
Medium
medium.com › @maximgradan › serialize-a-struct-to-bytes-to-send-it-through-the-network-in-go-part-i-b861c15d2f06
Serialize a struct to bytes to send it through the network in Go — Part I | by Maxim Gradan | Medium
June 2, 2022 - That’s why the real length of the struct is often greater than the length of its actual data. Moreover, this is a reason why you need to carefully pick an order of fields in your struct. Now you know why I mainly used a [16]byte array instead of a []byte slice.
🌐
GitHub
gist.github.com › SteveBate › 042960baa7a4795c3565
Example of converting a struct to a byte slice, compressing with gzip, and saving to file followed by the reverse process back to a struct · GitHub
Example of converting a struct to a byte slice, compressing with gzip, and saving to file followed by the reverse process back to a struct - struct_to_bytes.go
Top answer
1 of 11
51

One possible solution is the "encoding/gob" standard package. The gob package creates an encoder/decoder that can encode any struct into an array of bytes and then decode that array back into a struct. There's a great post, here.

As others have pointed out, it's necessary to use a package like this because structs, by their nature, have unknown sizes and cannot be converted into arrays of bytes.

I've included some code and a play.

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "log"
)

type P struct {
    X, Y, Z int
    Name    string
}

type Q struct {
    X, Y *int32
    Name string
}

func main() {
    // Initialize the encoder and decoder.  Normally enc and dec would be
    // bound to network connections and the encoder and decoder would
    // run in different processes.
    var network bytes.Buffer        // Stand-in for a network connection
    enc := gob.NewEncoder(&network) // Will write to network.
    dec := gob.NewDecoder(&network) // Will read from network.
    // Encode (send) the value.
    err := enc.Encode(P{3, 4, 5, "Pythagoras"})
    if err != nil {
        log.Fatal("encode error:", err)
    }

    // HERE ARE YOUR BYTES!!!!
    fmt.Println(network.Bytes())

    // Decode (receive) the value.
    var q Q
    err = dec.Decode(&q)
    if err != nil {
        log.Fatal("decode error:", err)
    }
    fmt.Printf("%q: {%d,%d}\n", q.Name, *q.X, *q.Y)
}
2 of 11
42

I assume you want something like the way C handles this. There is no built in way to do that. You will have to define your own serialization and deserialization to and from bytes for your struct. The binary package will help you encode the fields in your struct to bytes that you can add to the byte array but you will be responsible for specifying the lengths and offsets in the byte array that will hold the fields from your struct.

Your other options are to use one of the encoding packages: http://golang.org/pkg/encoding/ such as gob or json.

EDIT:

Since you want this for making a hash as you say in your comment the easisest thing to do is use []byte(fmt.Sprintf("%v", struct)) like so: http://play.golang.org/p/yY8mSdZ_kf

🌐
Igiven
igiven.com › dotnet-2021-05-01-Converting-between-Structs-and-Byte-Arrays
SeedNote - 最自由的笔记
May 1, 2021 - 截止至2022年9月4日,最新的IDEA版本为2022.2.1,对于某些想体验最新版IDEA却暂时没法入正的开发者来说,不能体验新版非常遗憾。 重置IDEA体验版的插件IDE Eval Resetter已经失效了,不过开发此插件的作者又开发出另一款工具...
🌐
Go Packages
pkg.go.dev › github.com › go-restruct › restruct
restruct package - github.com/go-restruct/restruct - Go Packages
December 27, 2019 - Unpack reads data from a byteslice into a value. Two types of values are directly supported here: Unpackers and structs.
🌐
Google Groups
groups.google.com › g › golang-nuts › c › QJaDAhl1WkY
convert bytes slice into structs
March 20, 2012 - to golan...@googlegroups.com · You have the declaration of F1 and F2 backwards. So it should be: type T1 struct { F1, F2 uint8 · } About skipping the 23 bytes: If its a file, I suggest you look into http://tip.golang.org/pkg/os/#File.Seek. Otherwise, you could just manually read from b.