为什么 Go 不会自动转换:
package main
import "fmt"
type Any interface{} // Any is an empty interface
type X func(x Any) // X is a function that receives Any
func Y(x X) { // Y is a function that receives X
x(1)
}
func test(v interface{}) { // test is not considered equal to X
fmt.Println("called",v)
}
func main() {
Y(test) // error: cannot use test (type func(interface {})) as type X in argument to Y
}
还有这个:
package main
import "fmt"
type Any interface{}
func X2(a Any) {
X(a)
}
func Y2(a interface{}) {
X2(a) // this is OK
}
func X(a ...Any) {
fmt.Println(a)
}
func Y(a ...interface{}) { // but this one not ok
X(a...) // error: cannot use a (type []interface {}) as type []Any in argument to X
}
func main() {
v := []int{1,2,3}
X(v)
Y(v)
}
我真的希望 interface{}
可以在任何东西(slices
、map
)上重命名为 Any
, func
) 不仅仅是简单的类型
第二个问题是:有没有办法让它成为可能?
最佳答案
第一个是关于type conversion和 type identity ,你有一套规则。
在“Why can I type alias functions and use them without casting?”中查看更多信息
type Any interface{}
是命名类型interface{}
是一个未命名的类型
它们的身份不同,不能用func(interface[})
代替func(Any)
。
第二个由 golang faq 涵盖
我可以将 []T
转换为 []interface{}
吗?
Not directly, because they do not have the same representation in memory.
It is necessary to copy the elements individually to the destination slice. This example converts a slice of int to a slice of interface{}:
t := []int{1, 2, 3, 4}
s := make([]interface{}, len(t))
for i, v := range t {
s[i] = v
}
有关内存表示的更多信息,请参见“what is the meaning of interface{}
in golang?”:
关于interface - Go 界面中的设计决策{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27310220/