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
我的问题是如何通过任何可能的输出作为参数来传递Func?
分析解答
可以将int
类型的值分配给interface{}
变量; func() int
类型的值无法分配给func() interface{}
类型的值。任何版本都是如此。
思想,您试图通过Go 1.18实现您尝试的操作,您可以在那里轻松type-parametrize与T any
的函数(btw any
是interface{}
的别名):
func callf[T any](f func() T) T {
return f()
}
func one() int {
return 1
}
type A struct {}
func two() A {
return A{}
}
func main() {
a := callf(one)
b := callf(two)
fmt.Println(a) // 1
fmt.Println(b) // {}
}