所以我一直在阅读这两篇文章和这个答案
无法将 []string 转换为 []interface {}表示需要更改内存布局。
http://jordanorelli.com/post/32665860244/how-to-use-interfaces-in-go说了解潜在的记忆使回答这个问题变得容易,并且
http://research.swtch.com/interfaces,解释了幕后发生的事情。
但就我的一生而言,就接口的实现而言,我想不出为什么 []T 不能转换为 []interface 的原因。
So Why?
文章《接口切片” 尝试详细说明:
有类型的变量[]interface{}
不是接口!它是一个切片,其元素类型恰好是interface{}
。但即便如此,人们可能会说含义是明确的。
嗯,是吗?有类型的变量[]interface{}
具有在编译时已知的特定内存布局。
Each interface{}
占用两个字(一个字代表所包含内容的类型,另一个字代表所包含的数据或指向它的指针)。因此,一个长度为 N 且类型为[]interface{}
由 N*2 个字长的数据块支持。
也可以看看 ”是什么意思interface{}在戈兰?"
这与支持类型切片的数据块不同[]MyType
并且长度相同。它的数据块将是N*sizeof(MyType)
话长。
结果是你无法快速分配某种类型[]MyType
某种类型的东西[]interface{}
;它们背后的数据只是看起来不同。
"why []string不能转换为[]interface{} in Go”补充了一个很好的例证:
// imagine this is possible
var sliceOfInterface = []interface{}(sliceOfStrings)
// since it's array of interface{} now - we can do anything
// let's put integer into the first position
sliceOfInterface[0] = 1
// sliceOfStrings still points to the same array, and now "one" is replaced by 1
fmt.Println(strings.ToUpper(sliceOfStrings[0])) // BANG!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)