Go:派生类型中嵌入类型字段的初始化

huangapple go评论91阅读模式
英文:

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)
}

huangapple
  • 本文由 发表于 2015年10月2日 19:22:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/32906086.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定