use gob to package recursively defined structs

放肆的年华 提交于 2019-12-07 12:19:40

问题


I mostly use Python, but am playing around with Go. I wrote the following to do something that is quite simple in python, and im hoping it can be accomplished in Go as well.

package main

import (
    "bytes"
    "encoding/gob"
    "fmt"
    "io/ioutil"
)

type Order struct {
    Text string
    User *User
}

type User struct {
    Text  string
    Order *Order
}

func main() {
    o := Order{}
    u := User{}
    o.Text = "order text"
    u.Text = "user text"

    // commenting this section prevents stack overflow
    o.User = &u
    u.Order = &o
    fmt.Println("o.u.text:", o.User.Text, "u.o.text:", u.Order.Text)
    // end section

    m := new(bytes.Buffer)
    enc := gob.NewEncoder(m)
    enc.Encode(o)
    err := ioutil.WriteFile("gob_data", m.Bytes(), 0600)
    if err != nil {
        panic(err)
    }
    fmt.Printf("just saved gob with %v\n", o)

    n, err := ioutil.ReadFile("gob_data")
    if err != nil {
        fmt.Printf("cannot read file")
        panic(err)
    }
    p := bytes.NewBuffer(n)
    dec := gob.NewDecoder(p)
    e := Order{}
    err = dec.Decode(&e)
    if err != nil {
        fmt.Printf("cannot decode")
        panic(err)
    }
    fmt.Printf("just read gob from file and it's showing: %v\n", e)

}

As you can see, there are two custom structs, each containing a reference to the other, recursively. When I try to package one up into a file using gob, it compiles, but i get a stack overflow, I am assuming this is caused by the recursion. In my experience, pickle handles things like this without a gasp. What am I doing wrong?


回答1:


As of now, the encoding/gob package doesn't work with recursive values:

Recursive types work fine, but recursive values (data with cycles) are problematic. This may change.

Until this is changed, you'll have to either not use cyclic data, or use a different approach to serialisation.



来源:https://stackoverflow.com/questions/26889287/use-gob-to-package-recursively-defined-structs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!