1

The code shown below, I create a struct type and want to encode it to binary. But it show binary.Write: invalid type main.Stu error, I had read some similar code like this,but I can't find why my code doesn't work?


type Stu struct {
    Name string
    Age int
    Id int
}

func main()  {
    s := &Stu{
        Name: "Leo",
        Age: 21,
        Id: 1,
    }

    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.BigEndian, s)
    if err != nil{
        fmt.Println(err)
    }
    fmt.Printf("%q\n", buf)
}
1
  • 3
    You did not read the documentation of encoding/binary.Write: "Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data."
    – Volker
    Jan 22, 2021 at 9:17

1 Answer 1

10

In short: encoding/binary cannot be used to encode arbitrary values that have non-fixed size. int and string are such examples. Quoting from binary.Write():

Write writes the binary representation of data into w. Data must be a fixed-size value or a slice of fixed-size values, or a pointer to such data.

Note that if you remove the string field and change int fields to int32, it'll work:

type Stu struct {
    Age int32
    Id  int32
}

func main() {
    s := &Stu{
        Age: 21,
        Id:  1,
    }

    buf := new(bytes.Buffer)
    err := binary.Write(buf, binary.BigEndian, s)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("%q\n", buf)
}

Which outputs (try it on the Go Playground):

"\x00\x00\x00\x15\x00\x00\x00\x01"

As the doc suggests, to encode complex structures, use encoding/gob.

Example of encoding and decoding using encoding/gob:

buf := new(bytes.Buffer)
enc := gob.NewEncoder(buf)
if err := enc.Encode(s); err != nil {
    fmt.Println(err)
}
fmt.Printf("%v\n", buf.Bytes())

dec := gob.NewDecoder(buf)
var s2 *Stu
if err := dec.Decode(&s2); err != nil {
    fmt.Println(err)
}
fmt.Printf("%+v\n", s2)

Which outputs (try it on the Go Playground):

[41 255 129 3 1 1 3 83 116 117 1 255 130 0 1 3 1 4 78 97 109 101 1 12 0 1 3 65 103 101 1 4 0 1 2 73 100 1 4 0 0 0 12 255 130 1 3 76 101 111 1 42 1 2 0]
&{Name:Leo Age:21 Id:1}
2
  • 3
    binary.Write can write structs. It can't write string or int because they're not fixed-size. Jan 22, 2021 at 9:17
  • @icza Thanks, I'll remeber it in my heart.
    – jett chen
    Jan 22, 2021 at 9:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.