Go conversion between struct and byte array

后端 未结 4 1958
慢半拍i
慢半拍i 2021-01-02 13:41

I am writing a client - server application in Go. I want to perform C-like type casting in Go.

E.g. in Go

type packet struct {
    opcode uint16
             


        
4条回答
  •  -上瘾入骨i
    2021-01-02 14:07

    unsafe.Pointer is, well, unsafe, and you don't actually need it here. Use encoding/binary package instead:

    // Create a struct and write it.
    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)
    

    Playground

    As you can see, it handles sizes and endianness quite neatly.

提交回复
热议问题