我是新手,遇到了以下问题,尽管我确定这一定是我所错过的语言的基本方面,但我在本教程或Google搜索中找不到该问题。 我有如下代码:

1
2
3
4
5
6
7
8
9
type Task func()

var f Task = func() { fmt.Println("foo") }

type TaskWithValue func() interface{}

var g TaskWithValue = func() { return"foo" }

var h TaskWithValue = func() { return 123 }

在上面的f中,没有编译器错误,但是对于gh,存在如下错误:

1
Cannot use func() { return"foo" } (type func ()) as type TaskWithValue in assignment

本质上,我试图定义一个可以具有任意返回类型的Task类型。 在其他语言中,我只是给Task一个类型参数,例如TaskTask,但是由于go没有泛型/模板,我知道解决方法是使用返回类型interface{},然后将其转换为 结果。 我想让这个示例正常工作吗?

您在匿名函数表达式中缺少返回类型:

1
2
3
var g TaskWithValue = func() interface{} { return"foo" }

var h TaskWithValue = func() interface{} { return 123 }