map [string] interface {}和interface {}之间的区别 [英] Difference between map[string]interface{} and interface{}

查看:214
本文介绍了map [string] interface {}和interface {}之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将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 {}之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆