Go conversion between struct and byte array

后端 未结 4 1988
慢半拍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条回答
  •  孤独总比滥情好
    2021-01-02 14:08

    I've had the same problem and I solved it by using the "encoding/binary" package. Here's an example:

    package main
    
    import (
      "bytes"
      "fmt"
      "encoding/binary"
    )
    
    func main() {
      p := fmt.Println
      b := []byte{43, 1, 0}
    
      myStruct := MyStruct{}
      err := binary.Read(bytes.NewBuffer(b[:]), binary.BigEndian, &myStruct)
    
      if err != nil {
        panic(err)
      }
    
      p(myStruct)
    }
    
    type MyStruct struct {
      Num uint8
      Num2 uint16
    }
    

    Here's the running example: https://play.golang.org/p/Q3LjaAWDMh

提交回复
热议问题