转:函数的变量,返回接口

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?

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.

This is a similar concept to: Can I convert a []T to an []interface{}?

Basically func() *Dummy is a different type from func() DummyInterface, and conversion between them is not possible.

You will need to use the interface throughout to make the function signature the same.