在Go语言中如何序列化递归类型

huangapple go评论88阅读模式
英文:

Marshal recursive types in go

问题

我想在Go语言中进行递归类型的编组和解组,类似于这样:

type Dog struct {
    age int
    sibling *Dog
}

在golang中有没有办法做到这一点?我尝试使用json.Marshal,但它不起作用。

英文:

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.

答案1

得分: 8

你的问题不是关于递归,而是理解Golang中的封装,即公有成员和私有成员。
为了在Go中进行编码,你的结构体必须具有公有字段(以大写字母开头):

type Dog struct {
    Age     int
    Sibling *Dog
}

完整示例:https://play.golang.org/p/eNdLaTfKtN

英文:

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

huangapple
  • 本文由 发表于 2016年10月25日 13:38:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/40232098.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定