Go interface{} 转 切片类型

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Go interface{} 转 切片类型

_wei丶   2022-05-23 我要评论

遇到这样一个情况想将变量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{} 就算是个切片类型也不能直接遍历,需要先转化
切片之间不能互相转化
接口类型的才可以进行断言

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们