在 Golang 中定义 returns 任意类型的函数

Defining a function that returns Any type in Golang

我想定义一个函数类型(我们在 C# 中称为委托),它的 return 值可以是任何东西(在编译类型时未知)并且在阅读 Golang 文档之后(从 3 天前)我开始学习 Golang)我发现该语言的当前版本不支持泛型。在搜索 Whosebug 之后,我遇到了一个 post 提示可以将 return 类型设置为 interface{},这意味着任何类型都可以被该函数 returned。然后我写了下面的代码来测试它是如何工作的:

type Consumer func() interface {}

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

但是我得到以下错误

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

这是当我将 Consumer 的 return 类型更改为 string 时,它没有任何问题。

问题是我做错了什么,我怎样才能编写一个可以 return 任何东西的函数类型(委托)并为其分配一个实际函数?

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

请试试这个

问题是函数类型func() string不符合函数类型func() interface{}

这是因为函数类型 func() interface{} 意味着函数显式 returns 类型 interface{} 的值,而 string 可以很容易地转换为 interface{},整体 函数签名 不同 相同。

正确的代码是:

type Consumer func() interface {}

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

字符串被隐式转换为 interface{} 类型,并且函数签名相同。