Home  >  Article  >  Backend Development  >  How to Convert Structs to Byte Arrays and Vice Versa in Go?

How to Convert Structs to Byte Arrays and Vice Versa in Go?

DDD
DDDOriginal
2024-10-27 22:02:02619browse

 How to Convert Structs to Byte Arrays and Vice Versa in Go?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn