栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

那么内存布局意味着[] T无法在Go中转换为[]接口?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

那么内存布局意味着[] T无法在Go中转换为[]接口?

文章“ 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!


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/392030.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号