inheritance - 转到 : How to reference a field in an inherited struct

标签 inheritance go struct

我有 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/

相关文章:

java - 有没有办法制作一个非抽象但必须被覆盖的方法?

go - 在Azure DevOps中为Go设置代码覆盖率

javascript - 继承问题

c++ - 为什么在这段代码中调用虚方法时会出现段错误?

go - 如何使用 Gin 构建带有标签的 golang 应用程序?

go - GO编译WASM导出函数

c - 将结构传递给 C 中的函数

xml - 解析动态 XML

C:生成随机字符串并将其添加到结构的函数

c# - 基类继承另一个基类?