Go Conversion Between Struct and Byte Array
Q: How can I perform C-like type casting between structs and byte arrays in Go? For example, how can I map a received network byte stream directly to a struct?
A: The encoding/binary package provides a more convenient and safer alternative to unsafe.Pointer:
<code class="go">// Create a struct and write it. type T struct { A uint32 B float64 } t := T{A: 0xEEFFEEFF, B: 3.14} buf := &bytes.Buffer{} err := binary.Write(buf, binary.BigEndian, t) if err != nil { panic(err) } fmt.Println(buf.Bytes()) // Read into an empty struct. t = T{} err = binary.Read(buf, binary.BigEndian, &t) if err != nil { panic(err) } fmt.Printf("%x %f", t.A, t.B)</code>
By utilizing the binary package, you can easily convert between structs and byte arrays in a safer and more concise manner, handling sizes and endianness automatically.
The above is the detailed content of How to Convert Structs to Byte Arrays and Vice Versa in Go?. For more information, please follow other related articles on the PHP Chinese website!