在同一结构类型内部使用Go结构体?

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

Go struct inside of same struct type?

问题

我想要一个结构体之间的关系,例如:

type A struct {
   X string
   Y int
   *A
}

这样做是可能的吗?
如果可能的话,正确的方法是如何将其编组和解组为 JSON?

当我将这个结构体编组为 JSON 时,字段 A 会丢失。

英文:

I want a relationship between structs, example:

type A struct {
   X string
   Y int
   *A
}

It's possible this?
And if it's possible, what is the right way to marshal and unmarshal to JSON this?

When i marshal this struct to JSON the field A is lost.

答案1

得分: 0

代码是正确的,但是匿名字段A丢失了,因为它与结构体具有相同的名称。
解决方案:

type A struct {
   X string
   Y int
   Z *A
}
英文:

The code is correct, but the anonimous filed A is lost because have the same names as the struct.
Solution:

type A struct {
   X string
   Y int
   Z *A
}

huangapple
  • 本文由 发表于 2016年12月15日 00:41:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/41147766.html
匿名

发表评论

匿名网友

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

确定