我想将JSON文件解析为 map [string] interface {} :
I want to parse a JSON file to a map[string]interface{}:
var migrations map[string]interface{} json.Unmarshal(raw, &migrations) fmt.Println(migrations["create_user"])但是我修改了代码以将数据指向 interface {} :
But I modified my code to point data to interface{}:
var migrations interface{} json.Unmarshal(raw, &migrations) // compile wrong here fmt.Println(migrations["create_user"])在上述情况下,我对 map [string] interface {} 和 interface {} 之间的区别了解不多.
I don't understand much about difference between map[string]interface{} and interface{} in above case.
推荐答案这是因为默认情况下,您需要键入assert interface {}以获取map [string] interface {}的基础值.
It is because by default you need to type assert interface{} to get the underlying value of map[string]interface{}.
根据 GoLang 规范
对于接口类型为T且类型为T的表达式x,主要表达
For an expression x of interface type and a type T, the primary expression
x.(T)断言x不是nil,并且存储在x中的值是T类型.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.
解组函数还需要指向interface {}或map [string] interface {}类型的 migration 的指针
Also Unmarshal function requires pointer to migration of type interface{} or map[string]interface{}
var migrations interface{} json.Unmarshal(raw, &migrations) fmt.Println(migrations.(interface{}).(map[string]interface{})["create_user"])由于 migrations 不是地图.因此,您不能使用其键来获取值.界面{}没有按键
Since migrations is not a map. So you cannot use its key to get the value. Interface{} don't have keys
更多推荐
map [string] interface {}和interface {}之间的区别
发布评论