Go结构可以继承一组值吗?

时间:2012-09-21 18:56:26

标签: inheritance go

Go结构可以从另一个结构的类型继承一组值吗?

像这样。

type Foo struct {
    Val1, Val2, Val3 int
}

var f *Foo = &Foo{123, 234, 354}

type Bar struct {
    // somehow add the f here so that it will be used in "Bar" inheritance
    OtherVal string
}

让我这样做。

b := Bar{"test"}
fmt.Println(b.Val2) // 234

如果没有,可以使用什么技术来实现类似的东西?

1 个答案:

答案 0 :(得分:8)

以下是如何在条形码中嵌入Foo结构:

type Foo struct {
    Val1, Val2, Val3 int
}
type Bar struct {
    Foo
    OtherVal string
}
func main() {
    f := &Foo{123, 234, 354}
    b := &Bar{*f, "test"}
    fmt.Println(b.Val2) // prints 234
    f.Val2 = 567
    fmt.Println(b.Val2) // still 234
}

现在假设您不希望复制值,并且如果b发生更改,您希望更改f。那么你不希望嵌入但使用指针组合:

type Foo struct {
    Val1, Val2, Val3 int
}
type Bar struct {
    *Foo
    OtherVal string
}
func main() {
    f := &Foo{123, 234, 354}
    b := &Bar{f, "test"}
    fmt.Println(b.Val2) // 234
    f.Val2 = 567
    fmt.Println(b.Val2) // 567
}

两种不同的组合,具有不同的能力。