Go interface{} 转切片类型的实现方法
作者:_wei丶 时间:2024-05-05 09:31:05
遇到这样一个情况想将变量v转化为[]string类型
var v interface{}
a := []interface{}{"1", "2"}
v = a // v 这时还是interface{} 但其实是个 []interface{}
newValue := v.([]string)
fmt.Println(newValue)
提示:
panic: interface conversion: interface {} is []interface {}, not []string [recovered]
panic: interface conversion: interface {} is []interface {}, not []string
提示我们不能直接换成[]string所以我们先转化为[]interface{}
newValue := v.([]interface{})
fmt.Println(newValue)
打印: [1 50]
然后我们试图将 []interface{} 转化为[]string
newValue := v.([]interface{})
s := newValue.([]string)
fmt.Println(s)
提示:invalid type assertion: newValue.([]string) (non-interface type []interface {} on left)
这里告诉我们只有接口类型的才可以进行断言所以这种方式是错误的
由于切片类型间不能互相直接转化所以需要展开遍历,然后对interface{}进行断言
var v interface{}
var s []string
a := []interface{}{"1", "2"}
v = a // v 这时还是interface{} 但其实是个 []interface{}
for _, val := range v.([]interface{}) {
?? ?s = append(s, val.(string))
}
fmt.Println(s)
到此成功转化完成
总结:
interface{} 就算是个切片类型也不能直接遍历,需要先转化
切片之间不能互相转化
接口类型的才可以进行断言
来源:https://blog.csdn.net/eight_eyes/article/details/119760954
标签:Go,interface{},切片
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
mysql联合索引的使用规则
2024-01-15 06:18:14
![](https://img.aspxhome.com/file/2023/8/115568_0s.png)
Vue自定义指令实现弹窗拖拽四边拉伸及对角线拉伸效果
2024-05-28 15:43:08
![](https://img.aspxhome.com/file/2023/5/123195_0s.jpg)
十行代码使用Python写一个USB病毒
2021-08-27 17:05:41
![](https://img.aspxhome.com/file/2023/3/69593_0s.jpg)
OpenCV-Python实现图像梯度与Sobel滤波器
2021-04-07 05:23:20
![](https://img.aspxhome.com/file/2023/5/82535_0s.png)
使用python图形模块turtle库绘制樱花、玫瑰、圣诞树代码实例
2022-07-11 05:28:15
![](https://img.aspxhome.com/file/2023/2/72852_0s.png)
IE6 iframe 横向滚动条问题
2009-01-18 13:31:00
Python数据分析pandas模块用法实例详解
2023-01-25 00:47:29
巧用正则表达式获取新闻中图片地址
2010-07-17 13:09:00
python 3利用BeautifulSoup抓取div标签的方法示例
2023-09-17 02:57:48
asp单主键高效通用分页存储过程
2009-02-23 19:21:00
通过Python绘制中国结的示例代码
2021-05-29 15:15:21
![](https://img.aspxhome.com/file/2023/4/102784_0s.png)
合理关闭XHTML标签
2008-06-25 13:20:00
必备的JS调试技巧汇总
2023-08-07 06:26:50
![](https://img.aspxhome.com/file/2023/0/55930_0s.gif)
ASP访问统计计数器代码
2008-03-20 13:33:00
Python教程之类型转换详解
2021-03-23 02:48:17
Pycharm使用远程linux服务器conda/python环境在本地运行的方法(图解))
2021-05-13 07:42:11
![](https://img.aspxhome.com/file/2023/8/105298_0s.jpg)
Python中常用的os操作汇总
2022-12-13 08:30:16
![](https://img.aspxhome.com/file/2023/2/75302_0s.png)
SQL语句解析执行的过程及原理
2024-01-26 21:11:55
![](https://img.aspxhome.com/file/2023/1/127571_0s.png)
一个带采集远程文章内容,保存图片,生成文件等完整的采集功能
2011-04-02 11:02:00
python实现自动更换ip的方法
2023-06-16 21:43:06