这个问题在这里已经有了答案:
Type func with interface parameter incompatible error
(1 个回答)
Accept function in argument with empty interface return type
(2 个回答)
Empty interface{} in function type
(2 个回答)
2年前关闭。
我无法解释为什么这段代码会 not编译:
package main
import "math/rand"
type ooThinAir func() interface{}
func Int() ooThinAir {
return func() int {
return rand.Intn(100)
}
}
func main() {
}
// fails with: cannot use func literal (type func() int) as type ooThinAir in return argument
给定,根据 GoLang 规范,that所有类型都实现空接口(interface)
interface{}
.为什么函数文字不能分配给类型 ooThinAir
?
最佳答案
任何类型都可以分配给接口(interface)。
包含接口(interface)的类型是另一回事。[]int
不能分配给 []interface{}
func() int
不能分配给 func() interface{}
你必须把整个东西变成一个interface{}
然后使用反射来处理结果。
因为[]int
可分配给 interface{}
, 和 func() int
可分配给 interface{}
.
关于go - 为什么返回 int 的函数文字不能分配给返回 interface{} 的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58127263/