文章“ InterfaceSlice
”尝试详细说明:
类型变量
[]interface{}不是接口!这是一个切片,其元素类型恰好是interface{}。但是即使这样,也可以说含义很清楚。好吧 具有类型的变量具有
[]interface{}特定的内存布局,在编译时已知。每个
interface{}单词占用两个单词(一个单词表示所包含内容的类型,另一个单词表示所包含的数据或指向它的指针)。结果,长度为N和类型的切片[]interface{}由N* 2个字长的数据块支持。
另请参阅“
golang中的含义是
interface{}什么?”
这与支持具有类型
[]MyType和相同长度的切片的数据块不同。它的数据块将是N*sizeof(MyType)字长。结果是您不能快速将某类型
[]MyType的东西分配给某种类型的东西[]interface{};它们背后的数据看起来不同。
“
为什么
[]string不能
[]interface{}在Go中转换为”添加了一个很好的例子:// imagine this is possiblevar sliceOfInterface = []interface{}(sliceOfStrings)// since it's array of interface{} now - we can do anything// let's put integer into the first positionsliceOfInterface[0] = 1// sliceOfStrings still points to the same array, and now "one" is replaced by 1fmt.Println(strings.ToUpper(sliceOfStrings[0])) // BANG!

![那么内存布局意味着[] T无法在Go中转换为[]接口? 那么内存布局意味着[] T无法在Go中转换为[]接口?](http://www.mshxw.com/aiimages/31/392030.png)
