【发布时间】:2021-12-27 10:01:38
【问题描述】:
func F(f func()interface{})interface{} {
return f()
}
func one() int {
return 1
}
type A struct {}
func two() A {
return A{}
}
func main() {
a := F(one)
b := F(two)
}
上面的代码会出错
cannot use one (type func() int) as type func() interface {} in argument to F
cannot use two (type func() A) as type func() interface {} in argument to F
我的问题是如何将具有任何可能输出的函数作为参数传递?
【问题讨论】:
-
您需要键入其他函数才能返回一个空接口。这东西总是让我进入 Go,我仍然不明白为什么它是这样设计的。我理解你的思路,int 应该被空接口覆盖,因此作为返回类型是有效的,但事实并非如此。