My goal is to have a linked data structure, this is, a struct with a reference to another struct, and so on, so I can encode it into my file system, and whenever I need it, decode it, so I restore the whole linked structure, with the same content.
Example:
I have these linked structures:
type A struct {
b *B
}
type B struct {
c []C
}
type C interface{}
I initialize them this way:
var c0 C = "foo"
var c1 C = "bar"
var b *B = &B{}
b.c = make([]C, 2)
b.c[0] = c0
b.c[1] = c1
var a A = A{}
a.b = b
fmt.Println(a)
// {$b_address}
fmt.Println(a.b)
// {[c0_address,c1_address]}
fmt.Println(a.b.c[0])
// foo
fmt.Println(a.b.c[1])
// bar
I would like to know how to encode A, having it persisted into a file, so I can decode it getting the same result. Addresses are not important, but the content is. I've tried it with encoding/gob
, with no success:
// encode
f, err := os.Create("data.gob")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
enc := gob.NewEncoder(f)
enc.Encode(a)
f.Close()
// decode
var a1 A
f, err = os.Open("data.gob")
if err != nil {
fmt.Println(1, err)
os.Exit(1)
}
dec := gob.NewDecoder(f)
dec.Decode(&a1)
if err != nil {
fmt.Println(2, err)
os.Exit(1)
}
f.Close()
fmt.Println(a1)
// {<nil>}
// expected {$b_address}
Full example: http://play.golang.org/p/2vxHR9BzNy
Is there a way to do this without making the fields public? Is there any existing solution so I don't need to reinvent the wheel?