为什么这个func类型转换在Go中失败?
上下文:我正在尝试将 type 转换为func(*interface{}) booltype func(*string) bool,但遇到了编译错误。Go 抱怨无法进行类型转换,但没有解释原因。最小重现如下:
代码:
type strIterFn func(*string) bool
func someFactory (_ []interface{}) func(*interface{}) bool {
return func(_ *interface{}) bool { return true }
}
func main() {
strs := []interface{}{"hello", "world"}
strIterFn(someFactory(strs)) // --> this line fails to compile
}
游乐场:https : //play.golang.org/p/oOSy50j_tKw
回答
因为 Go 中没有类型协变。
在 Go FAQ 中,它解释了:
Can I convert a []T to an []interface{}?不直接。语言规范不允许
这样做,因为这两种类型在内存中没有相同的表示。需要将元素单独复制到目标切片。
这是对切片的解释,但对于函数,这是相同的想法。
此外,我发现您的代码示例很奇怪。你为什么需要*interface{}?需要一个指向接口的指针是一个相当深奥的用例。
也许正确的方法是重新设计?如果您可以描述您要解决的实际问题,那么可能会有其他解决方案。