Go:嵌入类型在派生类型中的字段初始化
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)
}
这里到底发生了什么?对不起,如果它很明显,但我就是不明白。
要初始化组合对象,您必须像任何其他对象一样初始化嵌入字段:
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{
Base{10},
}
fmt.Println(d.Field)
}
来自语言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.
所以这就是它不的原因。
这里有两种可能的方法来解决该限制,每种方法都在以下函数中进行了说明:
func main() {
d := &Derived{
Base{Field: 10},
}
e := new(Derived)
e.Field = 20
fmt.Println(d.Field)
fmt.Println(e.Field)
}
这是有效的代码:
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)
}
这里到底发生了什么?对不起,如果它很明显,但我就是不明白。
要初始化组合对象,您必须像任何其他对象一样初始化嵌入字段:
package main
import (
"fmt"
)
type Base struct {
Field int
}
type Derived struct {
Base
}
func main() {
d := &Derived{
Base{10},
}
fmt.Println(d.Field)
}
来自语言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.
所以这就是它不的原因。
这里有两种可能的方法来解决该限制,每种方法都在以下函数中进行了说明:
func main() {
d := &Derived{
Base{Field: 10},
}
e := new(Derived)
e.Field = 20
fmt.Println(d.Field)
fmt.Println(e.Field)
}