簡體   English   中英

轉到:強制轉換類型無法將map [string] interface {}映射到map [string] string

[英]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)是類型斷言,而不是強制類型轉換。

Go編程語言規范

類型斷言

對於具有接口類型和類型T的表達式x ,主表達式

 x.(T) 

斷言x不是nil並且x存儲的值是T類型。 符號x.(T)稱為類型斷言。


去有轉換。

Go編程語言規范

轉換次數

轉換是形式為T(x)的表達式,其中T是類型, x是可以轉換為類型T的表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM