How to serialize/unserialize type struct in GO
package main import ( "bytes" "encoding/gob" "fmt" "log" ) type Data struct { id int name string } 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, name: "jackie"} enc, err := d.GobEncode() if err != nil { log.Fatal("encode error:", err) } e := new(Data) e.GobDecode(enc) fmt.Println(e) }
版权声明:本文为博主原创文章,未经博主允许不得转载。