问题描述
我主要使用Python,但我正在玩Go。我写了以下内容来完成python中非常简单的操作,我希望它也可以在Go中完成。 包主
$ b $导入(
字节
encoding / gob
fmt
io / ioutil
)
类型结构{
文本字符串
用户*用户
}
类型用户结构{
文本字符串
订单*订单
}
func main(){
o:=订单{}
u:=用户{}
o.Text =订单文本
u.Text =用户文本
//评论此部分可防止堆栈溢出
o.User =&u; b $ b u.Order =& amp ; o
fmt.Println(outext:,o.User.Text,uotext:,u.Order.Text)
//结束部分
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(刚刚储存gob with%v \\\
,o)
$ bn,err:= ioutil.ReadFile(gob_data)
if err!= nil {
fmt.Printf(can not read file)
panic(err)
}
p:= bytes.NewBuffer(n)
dec:= gob.NewDecoder(p)
e:= Order {}
err = dec.Decode(&e)
if err!= nil {
fmt.Printf(can not decode)
panic err)
}
fmt.Printf(从文件中读取gob并显示:%v \ n,e)
}
正如您所看到的,有两个自定义结构,每个自定义结构递归地包含对另一个的引用。当我试图用gob打包一个文件到一个文件时,它编译,但我得到一个堆栈溢出,我假设这是由递归引起的。根据我的经验,咸菜没有喘气处理这样的事情。我现在做错了什么?
截至目前, encoding / gob
使用递归值:
在这个改变之前,您不得不使用循环数据,或者使用不同的方法来序列化。
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?
As of now, the encoding/gob
package doesn't work with recursive values:
Until this is changed, you'll have to either not use cyclic data, or use a different approach to serialisation.
这篇关于使用gob打包递归定义的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!