Difference between map[string]interface{} and interface{}
来源:Golang技术栈
时间:2023-04-14 21:20:53 227浏览 收藏
学习Golang要努力,但是不要急!今天的这篇文章《Difference between map[string]interface{} and interface{}》将会介绍到golang等等知识点,如果你想深入学习Golang,可以关注我!我会持续更新相关文章的,希望对大家都能有所帮助!
问题内容
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"])
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"])
I don't understand much about difference between map[string]interface{} and
interface{} in above case.
正确答案
It is because by default you need to type assert interface{} to get the underlying value of map[string]interface{}.
As per GoLang Specification
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.
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"])
Since migrations is not a map. So you cannot use its key to get the value.
Interface{} don't have keys
今天关于《Difference between map[string]interface{} and interface{}》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于golang的内容请关注golang学习网公众号!
-
193 收藏
-
354 收藏
-
418 收藏
-
161 收藏
-
209 收藏
-
Golang · Go问答 | 11小时前 | 配置 · go · 环境变量 · strconv · 服务启动 · 容错 · 环境变量 strconv.ParseBool Go问答 布尔配置 配置回滚333 收藏
-
Golang · Go问答 | 14小时前 | golang · 路由 · net/http · Go问答 · ServeMux · 兼容迁移 · net/http 通配符 路径参数 ServeMux Go问答 Go 1.22 PathValue404 收藏
-
226 收藏
-
Golang · Go问答 | 1星期前 | 错误处理 · go · 性能 · bytes.Buffer · Go 1.26 · io.EOF 版本迁移 Go 1.26 bytes.Buffer.Peek 缓冲区预览428 收藏
-
488 收藏
-
160 收藏
-
158 收藏
-
Golang · Go问答 | 1星期前 | golang · 连接池 · database/sql · Go问答 · 数据库事务 · 连接池 事务 DBStats rows.Close Go database/sql374 收藏
-
271 收藏
-
Golang · Go问答 | 1星期前 | golang · 错误处理 · 泛型 · Go问答 · Go 1.26 · errors.As Go问答 Go 1.26 errors.AsType 泛型错误处理255 收藏
-
187 收藏
-
382 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 立即学习 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 立即学习 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 立即学习 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 立即学习 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 立即学习 485次学习