golang initilize inner struct object in nested structs

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

golang initilize inner struct object in nested structs

问题

我有一个嵌套的结构体:

type Posts struct {
    Id        int
    CreatedAt time.Time
    Data      struct {
        Title    string
        UserName string
    }
}

我想创建一个Data对象,但是var innerData Posts.Data似乎不起作用。我不想创建单独的Data struct,因为我计划通过拥有多个具有不同内部结构体命名为Data的结构体来避免名称冲突。

英文:

I have a nested struct

type Posts struct {
	Id        int
	CreatedAt time.Time
	Data      struct {
		Title    string
		UserName string
	}
}

I want to create a Data object but var innerData Posts.Data doesn't seem to work. I don't want to create separate Data struct because I'm planning to avoid name collusions by having multiple structs which will have different inner structs named Data.

答案1

得分: 4

你不能这样做。Posts.Data不是一个类型的名称。你唯一能做的是var innerData struct{ ... },但我确定你不想这样做,因为这样会重复,并且需要在两个地方进行更改。否则,你必须给它一个名称。这个名称不一定是Data,可以是PostData或其他使其唯一的名称。

英文:

You can't. Posts.Data isn't the name of a type. The only thing you could do is var innerData struct{ ... }, which I'm sure you don't want to because then you would have repetition and need to make changes in two places. Otherwise, you have to give it a name. That name doesn't have to be Data, it can be PostData or something to make it unique.

huangapple
  • 本文由 发表于 2015年7月10日 09:29:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/31331016.html
匿名

发表评论

匿名网友

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

确定