我不确定为什么以下转换不起作用:
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
For an expression
x
of interface type and a typeT
, the primary expressionx.(T)
asserts that
x
is notnil
and that the value stored inx
is of typeT
. The notationx.(T)
is called a type assertion.
Go 有转化。
The Go Programming Language Specification
Conversions are expressions of the form
T(x)
whereT
is a type andx
is an expression that can be converted to typeT
.
关于casting - Go:将 map[string]interface{} 转换为 map[string]string 的类型失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580054/