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

标签 casting go

我不确定为什么以下转换不起作用:

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

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 有转化。

The Go Programming Language Specification

Conversions

Conversions are expressions of the form T(x) where T is a type and x is an expression that can be converted to type T.

关于casting - Go:将 map[string]interface{} 转换为 map[string]string 的类型失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580054/

相关文章:

typescript - 将 TypeScript 的 InstanceType 泛型与抽象类一起使用?

swift - 数级 swift

c - C 中的符号扩展,char>unsigned char

json - 如何正确解码 Golang 中的无键 JSON 数组?

go-golang编译错误: type has no method

c++ - static_cast<T>(...) 是编译时还是运行时?

c++ - 具有两级指针的 const_cast

pointers - 为什么请求是一个指针变量?为什么不是引用变量?

go - 如何使用反射来检查结构字段的类型是否为接口(interface){}?

golang Unmarshal Struct In Function 不知道类型和依赖接口(interface)