Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
734 views
in Technique[技术] by (71.8m points)

go - What does the error "binary.Write: invalid type" mean?

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
", buf)
}
question from:https://stackoverflow.com/questions/65842245/what-does-the-error-binary-write-invalid-type-mean

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
", buf)
}

Which outputs (try it on the Go Playground):

"x00x00x00x15x00x00x00x01"

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
", buf.Bytes())

dec := gob.NewDecoder(buf)
var s2 *Stu
if err := dec.Decode(&s2); err != nil {
    fmt.Println(err)
}
fmt.Printf("%+v
", 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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...