简体   繁体   English

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

[英]Can a Go struct inherit a set of values?

Can a Go struct inherit a set of values from a type of another struct? Go结构可以从另一个结构的类型继承一组值吗?

Something like this. 像这样的东西。

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
}

Which would let me do this. 哪个让我这样做。

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

If not, what technique could be used to achieve something similar? 如果没有,可以使用什么技术来实现类似的东西?

Here's how you may embed the Foo struct in the Bar one : 以下是如何在条形码中嵌入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
}

Now suppose you don't want the values to be copied and that you want b to change if f changes. 现在假设您不希望复制值,并且如果f更改,您希望b更改。 Then you don't want embedding but composition with a pointer : 那么你不希望嵌入但使用指针组合:

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
}

Two different kind of composition, with different abilities. 两种不同的组合,具有不同的能力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM