![](/img/trans.png)
[英]Flutter: type 'List<Map<String, Object>>' is not a subtype of type 'List<Map<String, int>>' in type cast
[英]Go: Cast type fails for map[string]interface{} to map[string]string
我不確定為什么以下轉換不起作用:
import "fmt"
func main() {
v := map[string]interface{}{"hello": "world"}
checkCast(v)
}
func checkCast(v interface{}) {
_, isCorrectType := v.(map[string]string)
if !isCorrectType {
fmt.Printf("incorrect type") <------------- why does it enter this if statement?
return
}
}
map[string]interface{}
與map[string]string
。 類型interface{}
與類型string
。
如果它們都是map[string]string
:
package main
import "fmt"
func main() {
v := map[string]string{"hello": "world"}
checkCast(v)
}
func checkCast(v interface{}) {
_, isCorrectType := v.(map[string]string)
if !isCorrectType {
fmt.Printf("incorrect type")
return
}
}
輸出:
[no output]
語句v.(map[string]string)
是類型斷言,而不是強制類型轉換。
對於具有接口類型和類型
T
的表達式x
,主表達式x.(T)
斷言
x
不是nil
並且x
存儲的值是T
類型。 符號x.(T)
稱為類型斷言。
去有轉換。
轉換是形式為
T(x)
的表達式,其中T
是類型,x
是可以轉換為類型T
的表達式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.