dongzhang8680 2017-04-12 21:29
浏览 294
已采纳

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

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条回答 默认 最新

  • douba4275 2017-04-12 21:34
    关注

    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 }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度