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

I H*_*azy 3 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
}
Run Code Online (Sandbox Code Playgroud)

哪个让我这样做.

b := Bar{"test"}
fmt.Println(b.Val2) // 234
Run Code Online (Sandbox Code Playgroud)

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

Den*_*ret 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
}
Run Code Online (Sandbox Code Playgroud)

现在假设您不希望复制值,并且您希望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
}
Run Code Online (Sandbox Code Playgroud)

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