Go - 当有多个具有相同属性的自定义类型结构时,如何根据条件创建和初始化结构实例?

我还是 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 中可以做到这一点吗?


慕斯王
浏览 119回答 1
1回答

隔江千里

PersonA您可以通过在和中嵌入一个通用结构来做这样的事情PersonB。例如(游乐场链接):package mainimport "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 personInterfacefunc (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 personInterfacefunc (p PersonB) personMarker() {}type personInterface interface {    personMarker()}var smartPerson personInterfacefunc 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 WorldB: foo, bar, Hello World
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go