Declare a function type with an arbitrary return type in golang

huangapple go评论92阅读模式
英文:

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没有编译错误,但是对于gh,会出现以下错误:

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(&quot;foo&quot;) }

type TaskWithValue func() interface{}

var g TaskWithValue = func() { return &quot;foo&quot; }

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 &quot;foo&quot; } (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&lt;Integer&gt; or Task&lt;String&gt;, 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 &quot;foo&quot; }

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

huangapple
  • 本文由 发表于 2017年4月13日 05:29:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/43379955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定