I'm still new to Go and am facing a situation that needs some help here.
Assume there are two types of structs with the SAME attribute list:
type PersonA struct {
[long list of attributes...]
}
type PersonB struct {
[same long list of attributes...]
}
And I would like to create an instance and initialize based on some conditions like below:
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)
There are two problems here:
First - 'smartPerson' needs to be the instance type ascertained in the switch statement.
Second - the 'long list initialization' is the same for all conditions, so better to avoid repetition.
Is it possible to do this in Go?
CodePudding user response:
You can, do something like this by embedding a common struct in both PersonA and PersonB.
For example (playgound link):
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)
}
Outputs:
A: foo, bar, Hello World
B: foo, bar, Hello World
