Defining a function that returns Any type in Golang

Issue

I would like to define a function type (what we call delegate in C#) whose return value can be anything (is unknown at compile type) and after reading Golang docs (it’s just been 3 days since I started learning Golang) I found that the current version of the language does not support generics. After searching StackOverflow I came across a post suggesting that the return type can be set as interface{} which implies that any type can be returned by that function. Then I wrote the following code to test how it works:

type Consumer func() interface {}

func TestConsumer() Consumer {
    return func() string {
         return "ok"
    }
}

But I got the following error

cannot use func literal (type func() string) as type Consumer in return argument

This is while when I change the return type of Consumer to string, it works without any problem.

The question is what is that I am doing wrong and how can I achieve writing a function type (delegate) that can return anything and assign an actual functions to that?

Solution

The issue is that the function type func() string does not conform to the function type func() interface{}.

The reason for this is because the function type func() interface{} means a function that explicitly returns a value of type interface{}, and while a string can be easily casted to an interface{}, the overall function signatures are not the same.

The correct code would be:

type Consumer func() interface {}

func TestConsumer() Consumer {
    return func() interface{} {
         return "ok"
    }
}

The string gets implicity casted to the interface{} type, and the function signatures are the same.

Answered By – Daniel Liao

Answer Checked By – David Goodson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.