This question already has answers here:
json.Marshal(struct) returns “{}”

(3个答案)


4年前关闭。




我想像这样递归和解码一个递归类型:
type Dog struct {
    age int
    sibling *Dog
}

有什么办法可以在golang中做到这一点?我尝试使用json.Marshal,但无法正常工作。

最佳答案

您的问题不在于递归,而是可以理解使用Golang封装。公共(public)和私有(private)成员。
为了在Go中编码,您的结构必须具有公共(public)字段(以大写字母开头):

type Dog struct {
    Age     int
    Sibling *Dog
}

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

09-17 13:30
查看更多