【发布时间】:2015-09-02 06:09:57
【问题描述】:
我想了解为什么下面的代码 sn-p 无法编译。 Go 接受函数作为可能具有任何返回类型的函数参数的方式是什么?
package main
func main() {
test(a) // Error: cannot use a (type func() string) as type func() interface {} in argument to test
test(b) // Error: cannot use b (type func() int) as type func() interface {} in argument to test
}
func a() string {
return "hello"
}
func b() int {
return 1
}
func test(x func() interface{}) {
// some code...
v := x()
// some more code....
}
播放:https://play.golang.org/p/CqbuEZGy12
我的解决方案基于 Volker 的回答:
package main
import (
"fmt"
)
func main() {
// Wrap function a and b with an anonymous function
// that has an empty interface return type. With this
// anonymous function, the call signature of test
// can be satisfied without needing to modify the return
// type of function a and b.
test(func() interface{} {
return a()
})
test(func() interface{} {
return b()
})
}
func a() string {
return "hello"
}
func b() int {
return 1
}
func test(x func() interface{}) {
v := x()
fmt.Println(v)
}
【问题讨论】:
标签: go