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}