英文:
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
}
现在假设你不想复制值,并且希望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
}
两种不同类型的组合,具有不同的能力。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论