使用gob打包递归定义的结构

时间:2014-11-12 14:24:47

标签: go recursive-datastructures gob

我主要使用Python,但我正在玩Go。我写了以下内容来做一些在python中非常简单的事情,我希望它也可以在Go中完成。

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)

}

正如您所看到的,有两个自定义结构,每个结构都以递归方式包含对另一个结构的引用。当我尝试使用gob将一个打包到一个文件中时,它会编译,但是我得到一个堆栈溢出,我假设这是由递归引起的。根据我的经验,泡菜可以毫不费力地处理这样的事情。我做错了什么?

1 个答案:

答案 0 :(得分:5)

截至目前,encoding/gobdoesn't work具有递归值:

  

递归类型工作正常,但递归值(带循环的数据)是有问题的。这可能会改变。

在更改之前,您必须要么不使用循环数据,要么使用不同的方法进行序列化。