[英]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.