想用 []interface{} 类型来接受一个任意类型的数组,从而进行泛型操作时,发现直接赋值会发生错误,导致 panic
var dataSlice []int = foo()
var interfaceSlice []interface{} = dataSlice
cannot use dataSlice (type []int) as type []interface { } in assignment
先说结论: interface{} 可以接收任何类型,但是[]interface{} 并不可以接收任何类型的切片
[]interface{} 并不是 interface{},它是一个元素类型为 interface{} 的切片。
主要是因为 []interface{} 有特殊的内存布局。先看一下 []interface{} 的内存布局:
可是普通类型的切片内存布局是:
所以,根本原因就是两个东西的内存布局不同,即底层数据结构不同,所以无法直接赋值。
如果真的要 用[]interface{} 类型来接受一个任意类型的数组,可以用循环赋值的方式
var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
interfaceSlice[i] = d
}