Consider the following factory: Go playground
type TypeA struct {
placeholder int
}
func NewTypeA() *TypeA {
return new(TypeA)
}
func main() {
factory := make(map[string]func() interface{})
factory["TypeA"] = NewTypeA
}
This gives me the following error: cannot use NewTypeA (type func() *TypeA) as type func() interface {} in assignment
which is pretty clear.
I thought that interface{}
was able to be matched with a pointer.
I found this solution: Go playground
type Entity interface {}
type TypeA struct {
Entity
placeholder int
}
func NewTypeA() Entity {
return new(TypeA)
}
func main() {
var tmp interface{}
factory := make(map[string]func() Entity)
factory["TypeA"] = NewTypeA
tmp = factory["TypeA"]()
log.Println(reflect.TypeOf(tmp))
}
Which gives me the expected type *TypeA
.
Is there an other way to do this using the interface{}
type directly instead of a "dumb" interface (Entity
)?