lundi 25 juillet 2022

Assign an interface to an interface struct field in Golang

Consider we have an aggregation struct of interfaces

type Aggregation struct {
    a InterfaceA
    b InterfaceB
    ...
    n InterfaceN
}

we are trying to make the following function to initialize this struct's fields more funky -- to eliminate the switch:

func (a *Aggregation) Register(i interface{}) *Aggregation {
    switch v := i.(type) {
    case InterfaceA:
        a.a = v
    case InterfaceB:
        a.a = b
    ...
    case InterfaceN:
        a.a = v
    }
    return a
}

is there any way to accomplish the same functionality with reflection?





Aucun commentaire:

Enregistrer un commentaire