【问题标题】:use gob to package recursively defined structs使用 gob 封装递归定义的结构体
【发布时间】:2014-11-12 14:24:46
【问题描述】:

我主要使用 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 将一个打包到一个文件中时,它会编译,但我得到一个堆栈溢出,我假设这是由递归引起的。根据我的经验,pickle 可以毫不费力地处理这样的事情。我做错了什么?

【问题讨论】:

标签: go recursive-datastructures gob


【解决方案1】:

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

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

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

【讨论】:

  • 嘘...感谢您提供的信息,我当然希望他们最终会得到支持。喜欢在 python 中捕获内部状态。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-10-14
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多