Go:将map[string]interface{}转换为map[string]string时类型转换失败

5

我不确定为什么以下转换无法工作:

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
    }
}
1个回答

9

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)是类型断言,而不是类型转换。

The Go Programming Language Specification

Type assertions

For an expression x of interface type and a type T, the primary expression

x.(T)

asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.


Go有类型转换。

Go编程语言规范

类型转换

类型转换是指形如 T(x) 的表达式,其中 T 是一个类型,x 是一个可以被转换为类型 T 的表达式。


有没有在Go中进行类型转换的方法? - Karan
1
@Karan:请看我的修订答案。Go语言有转换功能。 - peterSO

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接