日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

Go?interface{}?轉(zhuǎn)切片類型的實(shí)現(xiàn)方法_Golang

作者:_wei丶 ? 更新時(shí)間: 2022-04-15 編程語言

遇到這樣一個(gè)情況想將變量v轉(zhuǎn)化為[]string類型

var v interface{}
a := []interface{}{"1", "2"}
v = a // v 這時(shí)還是interface{} 但其實(shí)是個(gè) []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所以我們先轉(zhuǎn)化為[]interface{}

newValue := v.([]interface{})
fmt.Println(newValue)

打?。?[1 50]

然后我們?cè)噲D將 []interface{} 轉(zhuǎn)化為[]string

newValue := v.([]interface{})
s := newValue.([]string)
fmt.Println(s)

提示:invalid type assertion: newValue.([]string) (non-interface type []interface {} on left)

這里告訴我們只有接口類型的才可以進(jìn)行斷言所以這種方式是錯(cuò)誤的

由于切片類型間不能互相直接轉(zhuǎn)化所以需要展開遍歷,然后對(duì)interface{}進(jìn)行斷言

var v interface{}
var s []string
a := []interface{}{"1", "2"}
v = a // v 這時(shí)還是interface{} 但其實(shí)是個(gè) []interface{}
for _, val := range v.([]interface{}) {
?? ?s = append(s, val.(string))
}
fmt.Println(s)

到此成功轉(zhuǎn)化完成

總結(jié):

interface{} 就算是個(gè)切片類型也不能直接遍歷,需要先轉(zhuǎn)化
切片之間不能互相轉(zhuǎn)化
接口類型的才可以進(jìn)行斷言

原文鏈接:https://blog.csdn.net/eight_eyes/article/details/119760954

欄目分類
最近更新