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 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答