douchanxiu5636 2014-06-05 03:48
浏览 80
已采纳

如何初始化继承对象的字段

I must be missing something. I cannot initialize an object's inherited fields without directly accessing them.

My goal is trying to keep it simple.

package main

type Page struct {
  Title string
}

type Article struct {
  Page
  Id int
}

func main() {

  // this generates a build error: 
  // "invalid field name Title in struct initializer"
  //
  p := &Article{
    Title: "Welcome!",
    Id:    2,
  }

  // this generates a build error: 
  // "invalid field name Page.Title in struct initializer"
  //
  p := &Article{
    Page.Title: "Welcome!",
    Id:         2,
  }

  // this works, but is verbose...  trying to avoid this
  //
  p := &Article{
    Id:    2,
  }
  p.Title = "Welcome!"

  // as well as this, since the above was just a shortcut
  //
  p := &Article{
    Id:    2,
  }
  p.Page.Title = "Welcome!"

}

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • douceng7070 2014-06-05 03:55
    关注

    In Go, these fields from embedded structs are called promoted fields.

    The Go Specification states (my emphasis):

    Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.

    This is how you can solve it:

    p := &Article{
        Page: Page{"Welcome!"},
        Id:   2,
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥15 基于作物生长模型下,有限水资源的最大化粮食产量的资源优化模型建立
  • ¥20 关于变压器的具体案例分析
  • ¥15 生成的QRCode圖片加上下載按鈕
  • ¥15 板材切割优化算法,数学建模,python,lingo
  • ¥15 科来模拟ARP欺骗困惑求解