use gob to package recursively defined structs

779 views Asked by At

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

There are 1 answers

1
Ainar-G On BEST ANSWER

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.