map [string] interface {}和interface {}之间的区别

编程入门 行业动态 更新时间:2024-10-21 20:29:29
本文介绍了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 {}之间的区别

本文发布于:2023-11-26 00:20:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631912.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:区别   map   string   interface

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!