我想了解为什么下面的代码片段无法编译。 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....
}
Play: https://play.golang.org/p/CqbuEZGy12 https://play.golang.org/p/CqbuEZGy12
我的解决方案基于沃尔克的回答:
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)
}
Play: https://play.golang.org/p/waOGBZZwN7 https://play.golang.org/p/waOGBZZwN7
对于 Go 新手来说,你犯了一个非常常见的误解:空接口interface{}
does not意思是“任何类型”。确实,事实并非如此。 Go 是静态类型的。空接口interface {}
是一个实际的(强类型类型),例如string
or struct{Foo int}
or interface{Explode() bool}
.
这意味着如果某物具有以下类型interface{}
它具有该类型而不是“任何类型”。
你的职能
func test(x func() interface{})
采用一个参数。这个参数是一个(无参数函数),它返回一个特定的类型,该类型interface{}
。您可以将任何函数传递给test
与此签名匹配:“无参数并返回interface{}
“。没有你的功能a
and b
匹配这个签名。
正如上面所说:interface {}
不是“whatever”的神奇缩写,它是一种独特的静态类型。
你必须改变,例如至:
func a() interface{} {
return "hello"
}
现在,当您返回一个时,这可能看起来很奇怪string
这不是类型interface{}
。这是有效的,因为任何类型都可以分配给类型的变量interface{}
(因为每种类型至少没有方法:-)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)