英文:
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)是一种类型断言,而不是类型转换。
对于接口类型的表达式
x和类型T,主表达式x.(T)断言
x不是nil,并且存储在x中的值是类型T。x.(T)的表示法称为类型断言。
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论