网络编程
位置:首页>> 网络编程>> Go语言>> Go interface{} 转切片类型的实现方法

Go interface{} 转切片类型的实现方法

作者:_wei丶  发布时间:2024-05-05 09:31:05 

标签:Go,interface{},切片

遇到这样一个情况想将变量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

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com