我有 2 个结构,其中一个继承了由 type Common struct {...}
表示的所有结构中共有的值
type Common struct{
Id int
CreatedAt time.Time
UpdatedAt time.Time
CreatorId int
}
type Post struct{
type Post struct{
Common
Status
Title string
ShortDescription string
Content string
CategoryIds []int
TagIds []int
Url string
MainImageId int
Keywords []string
}
但是,当我尝试创建 Post 结构的新实例时,如下所示。
post1 := &Post{
CreatorId: 1,
Status: 1,
Title: "this is the title of the first post",
ShortDescription: "this is the short description of this post",
Content: "",
Url: "first-post",
MainImageId: 1,
}
它不识别 CreatorId
字段。
我如何在新实例中引用此字段或修改结构,以便将 CreatorID
注册为 Post
结构的一部分?
谢谢
最佳答案
CreatorId
(顺便说一句,应该称为 CreatorID
)是 Сommon
的一部分,因此唯一的初始化方法是结构文字是:
post1 := &Post{
Common: Common{CreatorID: 1},
// ...
}
或者,
post1 := &Post{
// ...
}
post1.CreatorID = 1
关于inheritance - 转到 : How to reference a field in an inherited struct,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39618959/