gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:51:32 27 4
gpt4 key购买 nike

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

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com