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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。