4

I want to Marshal and Unmarshal a recursive type in go something like this:

type Dog struct {
    age int
    sibling *Dog
}

Is there any way to do this in golang? I tried with json.Marshal but it doesn't work.

Ross
  • 617
  • 2
  • 9
  • 23
  • What would be wrong with reading the documentation of json.Marshal (https://golang.org/pkg/encoding/json/#Marshal)? It describes your main problem (export your fields!) in the paragraph "The Go visibility rules..." and is clear on cyclic data structures: "JSON cannot represent cyclic data structures and Marshal does not handle them." (Maybe not your problem as "sibling" hints at a non-cyclic structure). Is it really faster/easier/more natural/better to ask on SO than read the official, complete and helpful documentation? – Volker Oct 25 '16 at 06:12

1 Answers1

8

Your problem is not with recursion, it's understand encapsulation with Golang, e.i. public and private members. In order to encode in Go, your struct has to have public fields (starting with Uppercase):

type Dog struct {
    Age     int
    Sibling *Dog
}

Full example: https://play.golang.org/p/eNdLaTfKtN

Yandry Pozo
  • 4,851
  • 3
  • 25
  • 27