網站首頁 編程語言 正文
遇到這樣一個情況想將變量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
相關推薦
- 2024-07-15 SpringBoot使用Apache Poi導出word文檔
- 2022-11-04 Android自定義View實現時鐘功能_Android
- 2022-05-09 C++智能指針shared_ptr_C 語言
- 2023-03-15 Android?Studio?全局查找問題_Android
- 2022-12-07 C++?Boost?Container庫示例詳細講解_C 語言
- 2023-07-05 React通過useContext特性實現組件數據傳遞
- 2022-09-18 Go語言實現文件上傳_Golang
- 2022-10-20 C++?float、double判斷是否等于0問題_C 語言
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支