【问题标题】:Go: embedded type's field initialization in derived typeGo:派生类型中嵌入类型的字段初始化
【发布时间】:2015-10-02 11:22:20
【问题描述】:

这是有效的代码:

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

这里到底发生了什么?对不起,如果很明显,但我就是不明白。

【问题讨论】:

  • 停止在 Go 中使用 BaseDerived 等术语。 Go 没有继承,如果你试图用一种包含组合的语言来思考继承,你只会让自己感到悲伤。

标签: go embedding


【解决方案1】:

来自语言specification

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

这就是为什么它不起作用

这里有两种可能的方法来解决该限制,每种方法都在以下函数中进行了说明:

func main() {
    d := &Derived{
        Base{Field: 10},
    }

    e := new(Derived)
    e.Field = 20

    fmt.Println(d.Field)
    fmt.Println(e.Field)
}

【讨论】:

    【解决方案2】:

    要初始化组合对象,您必须初始化嵌入字段,就像任何其他对象一样:

    package main
    
    import (
        "fmt"
    )
    
    type Base struct {
        Field int
    }
    
    type Derived struct {
        Base
    }
    
    func main() {
        d := &Derived{
            Base{10},
        }
        fmt.Println(d.Field)
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-10
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      相关资源
      最近更新 更多