我是RTFMing,特别是关于解码任意数据的部分.基于该部分,我编写了以下测试程序
var f interface{}
json.Unmarshal(
[]byte(`{"Name":"Wednesday","Age":6,"Parents":["Gomez","Morticia"]}`), &f)
m := f.(map[string]interface{})
for k, v := range m {
switch vv := v.(type) {
case string:
fmt.Println(k, "is string", vv)
case int:
fmt.Println(k, "is int", vv)
case []interface{}:
fmt.Println(k, "is an array:")
for i, u := range vv {
fmt.Println(i, u)
}
default:
fmt.Println(k, "is of a type I don't know how to handle")
fmt.Println(" Type Is:", vv)
}
}
Run Code Online (Sandbox Code Playgroud)
也就是说,我声明一个具有空接口类型的变量.按照文档,我
使用类型断言来访问f的底层映射[string] interface {}:
然后,我用来range对地图的键/值对进行for循环.如果值是字符串,int或[]接口,则程序会这样说.如果该值是另一种类型(默认情况),程序说我不知道如何处理它.这几乎是手册中的逐字典.
该程序产生以下输出.
Name is string Wednesday
Age is of a type I don't know how to handle
Type Is: 6
Parents is an array:
0 Gomez
1 Morticia
Run Code Online (Sandbox Code Playgroud)
那就是 - 它正确地识别字符串和数组的类型 - 由于某种原因,似乎解析的类型6不是和int- 它是6.
所以 - 我想我的问题是*为什么v.(type)在int这里返回实际数字或者我的问题是为什么这是错误的问题?
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |