繁体   English   中英

转到:如何在继承的结构中引用字段

[英]Go : How to reference a field in an inherited struct

我有2个结构,其中一个继承了所有type Common struct {...}表示的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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM