golang中为什么[]string 不能直接转换[]interface{}

栏目: Go · 发布时间: 5年前

内容简介:golang中,interface是可以被任意数量的类型满足,并且一个类型可以实现任意数量的接口。最后需要说明的是,每个类型都实现了一个空接口interface{}。任何类型(int、float、string、map、struct)都可赋值于interface{}。之前在前文(In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string to an inter

一、interface的泛型特性

golang中,interface是可以被任意数量的类型满足,并且一个类型可以实现任意数量的接口。最后需要说明的是,每个类型都实现了一个空接口interface{}。任何类型(int、float、string、map、struct)都可赋值于interface{}。之前在前文( https://www.jianshu.com/p/db192f49f843 )讲过了interface的结构。

二、golang中的转换原则

In Go, there is a general rule that syntax should not hide complex/costly operations. Converting a string to an interface{} is done in O(1) time. Converting a []string to an interface{} is also done in O(1) time since a slice is still one value. However, converting a []string to an []interface{} is O(n) time because each element of the slice must be converted to an interface{}.

翻译:

go 中,有一个共性原则:语法不应该存在复杂操作。 把string转换成interface{} 的时间复杂度是O(1)。转换[]string转换成interface{},也是O(1)。但转换[]string成[]interface{}需要的时间复杂度是O(n),因为slice中的每个元素都需要转换成interface{}

所以从上述可以看出,[]string 不能转换成[]interface{},是因为时间复杂度的原因,呃,这个解释其实有点牵强。

三、深层原因

[]string是一个字符数组,内存空间是

一是带有类型的变量[]interface{}不是接口!它是一个元素类型碰巧的切片interface{}。但即使考虑到这一点,也许可以说意义很明确。好吧,是吗?具有类型的变量具有[]interface{}特定的内存布局,在编译时已知。

二是每个interface{}单词占用两个成员变量(一个变量表示包含的内容,另一个变量表示包含的数据或指向它的指针)。因此,具有长度N和类型的切片[]interface{}由一长N * 2个字的数据块支持。

这与支持具有类型[]string和相同长度的切片的数据块不同。它的数据块将是N * sizeof(string)字长。

结果是你不能快速地将某种类型[]MyType的东西分配给某种类型的东西[]interface{}; 它们背后的数据看起来不同

根据上述的原因,可以推导出map[string]string 、map[string]struct 不能直接转换map[string]interface{}, []struct不能直接转换成[]interface{}。

如果非要转换,可以使用for 循环逐一转换,既简单又明了。


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Pro CSS and HTML Design Patterns

Pro CSS and HTML Design Patterns

Michael Bowers / Apress / April 23, 2007 / $44.99

Design patterns have been used with great success in software programming. They improve productivity, creativity, and efficiency in web design and development, and they reduce code bloat and complexit......一起来看看 《Pro CSS and HTML Design Patterns》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

图片转BASE64编码
图片转BASE64编码

在线图片转Base64编码工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具