【发布时间】:2013-11-03 20:07:45
【问题描述】:
相关代码:
type somethingFuncy func(int) bool
func funcy(i int) bool {
return i%2 == 0
}
var a interface{} = funcy
func main() {
_ = a.(func(int) bool) // Works
fmt.Println("Awesome -- apparently, literally specifying the func signature works.")
_ = a.(somethingFuncy) // Panics
fmt.Println("Darn -- doesn't get here. But somethingFuncy is the same signature as func(int) bool.")
}
第一个强制转换通过显式声明类型起作用。但第二个演员惊慌失措。为什么?有没有一种干净的方法可以转换为更长的 func 签名?
【问题讨论】:
-
somethingFuncy不是funcy(i int) bool的类型别名。这是一个全新的类型,定义为funcy(i int) bool。就像定义type A struct {Foo string}和type B struct{Foo string}一样。它们是不同的。