一个Go结构体能够继承一组值吗?

huangapple go评论83阅读模式
英文:

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 {
    // 以某种方式在这里添加f,以便在“Bar”继承中使用
    OtherVal string
}

这样我就可以这样做。

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

如果不行,有什么技术可以实现类似的效果?

英文:

Can a Go struct inherit a set of values from a type of another struct?

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?

答案1

得分: 9

这是如何在Bar结构体中嵌入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) // 打印234
	f.Val2 = 567
	fmt.Println(b.Val2) // 仍然打印234
}

现在假设你不想复制值,并且希望bf改变时也改变。那么你不想使用嵌入,而是使用指针进行组合:

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
}

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

英文:

Here's how you may embed the Foo struct in the Bar one :

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. 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.

huangapple
  • 本文由 发表于 2012年9月22日 02:56:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/12536574.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定