4

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?

2 Answers 2

5

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.
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, your description is helpful, but this still seems to contradict this behaviour, no? "T is an interface type and x implements T."
@obeattie: func() DummyInterface is not an interface type, it's a function type. DummyInterface is an interface type.
I guess not, since T is a function type in this case.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.