How do I dump the struct into the byte array without reflection?

前端 未结 1 1470
独厮守ぢ
独厮守ぢ 2020-12-13 15:14

I already found encoding/binary package to deal with it, but it depended on reflect package so it didn\'t work with uncapitalized(that is, unexported) struct fields. However

相关标签:
1条回答
  • 2020-12-13 15:27

    Your best option would probably be to use the gob package and let your struct implement the GobDecoder and GobEncoder interfaces in order to serialize and deserialize private fields.

    This would be safe, platform independent, and efficient. And you have to add those GobEncode and GobDecode functions only on structs with unexported fields, which means you don't clutter the rest of your code.

    func (d *Data) GobEncode() ([]byte, error) {
        w := new(bytes.Buffer)
        encoder := gob.NewEncoder(w)
        err := encoder.Encode(d.id)
        if err!=nil {
            return nil, err
        }
        err = encoder.Encode(d.name)
        if err!=nil {
            return nil, err
        }
        return w.Bytes(), nil
    }
    
    func (d *Data) GobDecode(buf []byte) error {
        r := bytes.NewBuffer(buf)
        decoder := gob.NewDecoder(r)
        err := decoder.Decode(&d.id)
        if err!=nil {
            return err
        }
        return decoder.Decode(&d.name)
    }
    
    func main() {
        d := Data{id: 7}
        copy(d.name[:], []byte("tree"))
        buffer := new(bytes.Buffer)
        // writing
        enc := gob.NewEncoder(buffer)
        err := enc.Encode(d)
        if err != nil {
            log.Fatal("encode error:", err)
        }
        // reading
        buffer = bytes.NewBuffer(buffer.Bytes())
        e := new(Data)
        dec := gob.NewDecoder(buffer)
        err = dec.Decode(e)
        fmt.Println(e, err)
    }
    
    0 讨论(0)
提交回复
热议问题