为什么此func类型转换在Go中失败?
上下文:我试图将类型为什么此func类型转换在Go中失败?,go,Go,上下文:我试图将类型func(*interface{})bool转换为类型func(*string)bool,但遇到编译错误。Go抱怨类型转换不可能,但没有解释原因。最低要求如下: 代码: type strIterFn func(*string) bool func someFactory (_ []interface{}) func(*interface{}) bool { return func(_ *interface{}) bool { return true } } func m
func(*interface{})bool
转换为类型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
}
操场:因为Go中没有类型协方差 在Go常见问题解答中,它解释了: 不直接。语言规范不允许它,因为
这两种类型在内存中没有相同的表示形式。它是 需要将元素单独复制到目标切片 这是对切片的一种解释,但对函数的解释是相同的
此外,我觉得你的代码样本很奇怪。为什么需要
*接口{}
?需要指向接口的指针是一个相当深奥的用例
也许正确的方法是重新设计?如果您能描述您试图解决的实际问题,可能会有其他解决方案。代码应该做什么,以及为什么您认为它应该工作?转换是不可能的,因为签名不匹配。
interface{}
并不意味着“任何类型”,它的字面意思是interface{}
没有其他内容。^谢谢,谢谢!是的,我会重新设计。
Can I convert a []T to an []interface{}?