dongse3348 2016-09-21 14:07
浏览 24
已采纳

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

I have 2 structs whereby one inherits values that are common amongst all stucts denoted by 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
}

However when I try to create a new instance of the Post struct as in the following.

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,
}

It does not recognise the CreatorId field. How would I reference this field in the new instance or modify the struct so that it registers CreatorID as part of the Post struct? Thanks

  • 写回答

1条回答 默认 最新

  • douwa0280 2016-09-21 14:16
    关注

    CreatorId (which, by the way should be called CreatorID) is a part of Сommon, so the only way to initialize it in struct literal is:

    post1 := &Post{
        Common: Common{CreatorID: 1},
        // ...
    }
    

    Alternatively,

    post1 := &Post{
        // ...
    }
    post1.CreatorID = 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 51寻迹小车定点寻迹
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站
  • ¥15 滑块验证码移动速度不一致问题
  • ¥15 Utunbu中vscode下cern root工作台中写的程序root的头文件无法包含
  • ¥15 麒麟V10桌面版SP1如何配置bonding
  • ¥15 Marscode IDE 如何预览新建的 HTML 文件