繁体   English   中英

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

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

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

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

以下是如何在条形码中嵌入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
}

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

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
}

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

暂无
暂无

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

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