在golang中声明一个具有任意返回类型的函数类型

时间:2017-04-12 21:29:08

标签: go

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

// I can't find where the {{component}} helper is located.
import Component from './???'

export default Component.extend({
     compute(componentType, hash) {
         let componentName = getComponentToRender(componentType);
         this._super(componentName, hash)
     }
})

在上面的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 } 中,没有编译器错误,但对于fg,存在如下错误:

h

基本上,我正在尝试定义一个可以具有任意返回类型的Cannot use func() { return "foo" } (type func ()) as type TaskWithValue in assignment 类型。在其他语言中,我只是给Task一个类型参数,例如TaskTask<Integer>,但由于go没有泛型/模板,我理解解决方法是使用返回类型{ {1}}然后投射结果。为了让这个例子有效,我错过了什么?

1 个答案:

答案 0 :(得分:2)

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

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

var h TaskWithValue = func() interface{} { return 123 }
相关问题