我还是 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 中可以做到这一点吗?
隔江千里
相关分类