我们可以使用可变参数函数和反射。
这是example code:
package main
import (
"errors"
"fmt"
"reflect"
)
type Parent struct {
A ChildA
B ChildB
C ChildC
D ChildD
}
type ChildA struct {
x string
}
type ChildB struct {
x string
}
type ChildC struct {
}
type ChildD struct {
}
func helper(childs ...any) (Parent, error) {
check := make(map[string]int)
var p Parent
for _, v := range childs {
if v == nil {
continue
}
childType := reflect.TypeOf(v)
check[childType.String()]++
if check[childType.String()] > 1 {
return p, errors.New("child must be unique")
}
switch childType.String() {
case "main.ChildA":
p.A = v.(ChildA)
case "main.ChildB":
p.B = v.(ChildB)
case "main.ChildC":
p.C = v.(ChildC)
case "main.ChildD":
p.D = v.(ChildD)
}
}
return p, nil
}
func main() {
p, err := helper(ChildA{"hello"}, ChildB{"world"}, ChildC{})
if err != nil {
panic(err)
}
fmt.Println(p)
}