我是Go的新手,我想了解为什么下面的代码片段无法编译.接受函数作为可能具有任何返回类型的函数参数的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....
}
Run Code Online (Sandbox Code Playgroud)
播放: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)
}
Run Code Online (Sandbox Code Playgroud)
Vol*_*ker 12
你绊倒了围棋新人一个非常普遍的误解:空接口interface{}并不能意味着"任何类型".真的,它没有.Go是静态类型的.空接口interface {}是实际的(强类型类型),例如eg string或struct{Foo int}or interface{Explode() bool}.
这意味着如果某些东西具有该类型的interface{}类型而不是"任何类型".
你的功能
func test(x func() interface{})
Run Code Online (Sandbox Code Playgroud)
取一个参数.此参数是(无参数函数),它返回特定类型,即类型interface{}.您可以传递test与此签名匹配的任何函数:"无参数并返回interface{}".您的所有功能都a和b匹配此签名.
如上所述:interface {}不是"无论"的神奇缩写,它是一种独特的静态类型.
你必须改变例如:
func a() interface{} {
return "hello"
}
Run Code Online (Sandbox Code Playgroud)
现在,当你返回一个string不属于类型的东西时,这可能看起来很奇怪interface{}.这是有效的,因为任何类型都可以赋值给类型的变量interface{}(因为每个类型至少没有方法:-).
| 归档时间: |
|
| 查看次数: |
4870 次 |
| 最近记录: |