英文:
How to initialize inherited object's fields
问题
我一定是漏掉了什么。我无法直接访问对象的继承字段来初始化它们。
我的目标是保持简单。
package main
type Page struct {
Title string
}
type Article struct {
Page
Id int
}
func main() {
// 这会生成一个构建错误:
// "在结构体初始化器中,无效的字段名 Title"
//
p := &Article{
Title: "欢迎!",
Id: 2,
}
// 这会生成一个构建错误:
// "在结构体初始化器中,无效的字段名 Page.Title"
//
p := &Article{
Page.Title: "欢迎!",
Id: 2,
}
// 这样可以工作,但是比较冗长...我试图避免这种情况
//
p := &Article{
Id: 2,
}
p.Title = "欢迎!"
// 以及这样,因为上面只是一种快捷方式
//
p := &Article{
Id: 2,
}
p.Page.Title = "欢迎!"
}
提前感谢。
英文:
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.
答案1
得分: 32
在Go语言中,来自嵌入结构体的这些字段被称为提升字段。
Go语言规范中指出(我强调):
>提升字段的行为类似于结构体的普通字段,但不能在结构体的复合字面值中用作字段名。
以下是解决方法:
p := &Article{
Page: Page{"Welcome!"},
Id: 2,
}
英文:
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,
}
答案2
得分: 7
你必须像这样进行初始化:
p := &Article{
Page: Page{
Title: "欢迎!",
},
Id: 2,
}
PlayGround: http://play.golang.org/p/CEUahBLwCT
package main
import "fmt"
type Page struct {
Title string
}
type Article struct {
Page
Id int
}
func main() {
// 这会生成一个构建错误:
// "在结构初始化器中的无效字段名 Title"
//
p := &Article{
Page: Page{
Title: "欢迎!",
},
Id: 2,
}
fmt.Printf("%#v \n", p)
}
英文:
You have to init like this:
p := &Article{
Page: Page{
Title: "Welcome!",
},
Id: 2,
}
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论