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