我還是 Go 的新手,并且在這里面臨需要一些幫助的情況。
假設有兩種型別的結構具有相同的屬性串列:
type PersonA struct {
[long list of attributes...]
}
type PersonB struct {
[same long list of attributes...]
}
我想創建一個實體并根據以下條件進行初始化:
var smartPerson [type]
func smartAction(personType string) {
switch personType
case "A":
smartPerson = PersonA{long list initialization}
case "B":
smartPerson = PersonB{same long list initialization}
}
fmt.Println(smartPerson)
這里有兩個問題:
首先 - 'smartPerson' 需要是在 switch 陳述句中確定的實體型別。
其次 - '長串列初始化'對于所有條件都是相同的,因此最好避免重復。
在 Go 中可以做到這一點嗎?
uj5u.com熱心網友回復:
PersonA您可以通過在和中嵌入一個通用結構來做這樣的事情PersonB。
例如(游樂場鏈接):
package main
import "fmt"
type commonPerson struct {
A string
B string
C string
}
type PersonA struct {
commonPerson
}
func (p PersonA) String() string {
return fmt.Sprintf("A: %s, %s, %s", p.A, p.B, p.C)
}
// This function is just here so that PersonA implements personInterface
func (p PersonA) personMarker() {}
type PersonB struct {
commonPerson
}
func (p PersonB) String() string {
return fmt.Sprintf("B: %s, %s, %s", p.A, p.B, p.C)
}
// This function is just here so that PersonB implements personInterface
func (p PersonB) personMarker() {}
type personInterface interface {
personMarker()
}
var smartPerson personInterface
func smartAction(personType string) {
common := commonPerson{
A: "foo",
B: "bar",
C: "Hello World",
}
switch personType {
case "A":
smartPerson = PersonA{commonPerson: common}
case "B":
smartPerson = PersonB{commonPerson: common}
}
}
func main() {
smartAction("A")
fmt.Println(smartPerson)
smartAction("B")
fmt.Println(smartPerson)
}
輸出:
A: foo, bar, Hello World
B: foo, bar, Hello World
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/417945.html
標籤:
上一篇:函式的語法
