Go: Variable to a function, returning an interface
go
Solution
Because `*Dummy` is not the same type as `DummyInterface`. The rule that you can assign an object to something of an interface type that object implements only applies in that literal case. If the interface type appears in one of the parameters of a type (i.e. the return type of a function), assignment is not possible.
Refer to the assignability rules for more information.
Assignability
A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
- x's type is identical to T.
- x's type V and T have identical underlying types and at least one of V or T is not a named type.
- T is an interface type and x implements T.
- x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
- x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
- x is an untyped constant representable by a value of type T.
Problem
In Go, why can I not have a variable to a function, which returns an interface type? Here's a minimal test case: ``` type DummyInterface interface { Method(string) string } // Dummy implements the DummyInterface interface type Dummy struct{} func (d Dummy) Method(i string) string { return i } // DummyFunc returns a Dummy pointer (which implements the DummyInterface interface) var DummyFunc (func() *Dummy) = func() *Dummy { a := Dummy{} return &a } // DummyInterfaceFunc is declared as returning function returning an object which implements DummyInterface -- it // is set to DummyFunc, which does return a conforming object var DummyInterfaceFunc (func() DummyInterface) = DummyFunc ``` This fails to compile (Playground example here), stating: ``` cannot use DummyFunc (type func() *Dummy) as type func() DummyInterface in assignment ``` Yet, as you can see, a `*Dummy` does implement `DummyInterface`. Why is this?