英文:
Go: embedded type's field initialization in derived type
问题
这里是可以工作的代码:
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{}
d.Field = 10
fmt.Println(d.Field)
}
这是无法编译的代码,会出现错误信息 ./main.go:17: unknown Derived field 'Field' in struct literal
:
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{
Field: 10,
}
fmt.Println(d.Field)
}
这里到底发生了什么?如果这显而易见,我很抱歉,但我就是不明白。
英文:
Here is the code that works:
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{}
d.Field = 10
fmt.Println(d.Field)
}
And here's the code that fails to compile with ./main.go:17: unknown Derived field 'Field' in struct literal
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{
Field: 10,
}
fmt.Println(d.Field)
}
What exactly is going on here? Sorry if it's obvious, but I just don't understand.
答案1
得分: 5
根据语言规范中的说明:
提升字段(Promoted fields)的行为类似于结构体的普通字段,但是它们不能在结构体的复合字面值中用作字段名。
所以这就是为什么它不起作用。
以下是两种可能的解决方法,每种方法都在下面的函数中进行了示例:
func main() {
d := &Derived{
Base{Field: 10},
}
e := new(Derived)
e.Field = 20
fmt.Println(d.Field)
fmt.Println(e.Field)
}
英文:
From the language specification:
> Promoted fields act like ordinary fields of a struct except that they cannot be used as field names in composite literals of the struct.
So that's why it doesn't work.
Here are two possible ways to work around that limitation, each illustrated in the following function:
func main() {
d := &Derived{
Base{Field: 10},
}
e := new(Derived)
e.Field = 20
fmt.Println(d.Field)
fmt.Println(e.Field)
}
答案2
得分: 1
要初始化组合对象,您需要初始化嵌入字段,就像初始化任何其他对象一样:
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{
Base{10},
}
fmt.Println(d.Field)
}
请注意,以上代码是用Go语言编写的。
英文:
To initialize composed objects you have to initialize the embedded field, like any other object:
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{
Base{10},
}
fmt.Println(d.Field)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论