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

huangapple go评论76阅读模式
英文:

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")  // 为什么会进入这个if语句?
        return
    }
}

这段代码中,checkCast 函数尝试将 v 转换为 map[string]string 类型。如果转换成功,isCorrectType 的值将为 true,否则为 false。在这种情况下,由于 v 的类型是 map[string]interface{},而不是 map[string]string,所以转换失败,isCorrectType 的值为 false,因此进入了 if 语句块并打印了 "incorrect type"。

英文:

I wasn't sure why the following casting doesn't work:

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
    }
}

输出:

[无输出]

语句v.(map[string]string)是一种类型断言,而不是类型转换。

Go编程语言规范

类型断言

对于接口类型的表达式x和类型T,主表达式

x.(T)

断言x不是nil,并且存储在x中的值是类型Tx.(T)的表示法称为类型断言。

Go语言支持类型转换。

Go编程语言规范

转换

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

英文:

map[string]interface{} is not the same as map[string]string. Type interface{} is not the same as type string.

If they are both 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
	}
}

Output:

[no output]

The statement v.(map[string]string) is a type assertion, not a cast.

> 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 has conversions.

> 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.

huangapple
  • 本文由 发表于 2014年7月5日 03:40:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/24580054.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定