英文:
Declare a function type with an arbitrary return type in golang
问题
我是你的中文翻译助手,以下是翻译好的内容:
我刚开始学习Go语言,遇到了一个问题,在教程和谷歌搜索中都没有找到相关的解答,但我相信这一定是我错过的语言基础知识。我有以下的代码:
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
没有编译错误,但是对于g
和h
,会出现以下错误:
Cannot use func() { return "foo" } (type func()) as type TaskWithValue in assignment
实际上,我想定义一个Task
类型,它可以具有任意的返回类型。在其他语言中,我可以简单地给Task
添加一个类型参数,比如Task<Integer>
或Task<String>
,但是由于Go语言没有泛型/模板,我了解到的解决方法是使用返回类型interface{}
,然后进行类型转换。请问我在这个例子中漏掉了什么?
英文:
I'm new to go and have come across the following issue that I haven't been able to find covered in the tutorial or google searches, though I'm sure it must be a basic aspect of the language I have missed. I have code like the following:
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 }
In f
above, there is no compiler error, but for g
and h
there are errors like the following:
Cannot use func() { return "foo" } (type func ()) as type TaskWithValue in assignment
Essentially, I'm trying to define a Task
type that can have an arbitrary return type. In other languages, I would simply give Task
a type parameter, like Task<Integer>
or Task<String>
, but since go does not have generics/templates, I understood the workaround is to use return type interface{}
and then cast the results. What am I missing to get this example working?
答案1
得分: 4
你在匿名函数表达式中缺少返回类型:
var g TaskWithValue = func() interface{} { return "foo" }
var h TaskWithValue = func() interface{} { return 123 }
英文:
You're missing the return type in the anonymous function expressions:
var g TaskWithValue = func() interface{} { return "foo" }
var h TaskWithValue = func() interface{} { return 123 }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论