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

edu*_*911 10 go

我肯定错过了什么.我无法在不直接访问对象的情况下初始化对象的继承字段.

我的目标是努力保持简单.

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!"

}
Run Code Online (Sandbox Code Playgroud)

提前致谢.

ANi*_*sus 24

在Go中,嵌入式结构中的这些字段称为提升字段.

Go规范说明(我的重点):

提升字段的作用类似于结构的普通字段,除了它们不能用作结构的复合文字中的字段名称.

这是你如何解决它:

p := &Article{
    Page: Page{"Welcome!"},
    Id:   2,
}
Run Code Online (Sandbox Code Playgroud)


fab*_*ioM 6

你必须这样初始化:

p := &Article{
    Page: Page{
        Title: "Welcome!",
    },
    Id: 2,
}
Run Code Online (Sandbox Code Playgroud)

PlayGround:http://play.golang.org/p/CEUahBLwCT

package main

import "fmt"

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{
        Page: Page{
            Title: "Welcome!",
        },
        Id: 2,
    }
    fmt.Printf("%#v \n", p)
}
Run Code Online (Sandbox Code Playgroud)