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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.