英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论