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

學無先后,達者為師

網站首頁 編程語言 正文

Go?interface{}?轉切片類型的實現方法_Golang

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

遇到這樣一個情況想將變量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

欄目分類
最近更新