在 golang 中 nil map 和空 map 有何不同?
而空 map 是一个已分配了内存但里面没有任何键值对的 map。在实际开发中,我们可以直接使用一个空 map,而无需再次初始化。同时,在遍历空 map 时不会进入循环。因为没有任何键值对可以遍历。
-
上一篇
在 golang 中 nil map 和空 map 有何不同?
<p class="ql-align-justify"><span style="color: rgb(18, 18, 18);">1)可以对未初始化的map进行取值,但取出来的东西是空:</span></p><p><span style="color: rgb(18, 18, 18);">var m1 map[string]string</span></p><p><span style="color: rgb(18, 18, 18);">fmt.Println(m1["1"])</span></p><p><span style="color: rgb(18, 18, 18);">////////////////////////////////////////////////////////////////////////////////</span></p><p class="ql-align-justify"><span style="color: rgb(18, 18, 18);">2)不能对未初始化的map进行赋值,这样将会抛出一个异常:</span></p><p><span style="color: rgb(18, 18, 18);">var m1 map[string]string</span></p><p><span style="color: rgb(18, 18, 18);">m1["1"] = "1"</span></p><p><span style="color: rgb(18, 18, 18);">panic: assignment to entry in nil map</span></p><p><span style="color: rgb(18, 18, 18);">////////////////////////////////////////////////////////////////////////////////</span></p><p class="ql-align-justify"><span style="color: rgb(18, 18, 18);">3) 通过fmt打印map时,空map和nil map结果是一样的,都为map[]。所以,这个时候别断定map是空还是nil,而应该通过map == nil来判断。</span></p><p><br></p><p><strong style="color: rgb(18, 18, 18);">nil map 未初始化,空map是长度为空</strong></p>
-
下一篇
在 golang 中 nil map 和空 map 有何不同?
在 golang 中 nil map 和空 map 有何不同?
相关文章
- 在PHP中,Magic Method都有哪些,并举例说明它们的作用?
- 如何通过PHP来保护您的代码免受SQL注入攻击?
- 请列出与PHP相关的缓存机制及其优缺点。
- 请给一个例子解释一下PHP中的闭包函数是什么?
- 如何在Golang中进行并发编程?
- 请解释下PHP中会话(session)和Cookie(cookie)的作用。
- PHP中如何处理文件上传和下载?
- 如何在Golang中实现单例模式?
- 请举例说明PHP中如何处理异常?
- 请谈谈您对PHP的垃圾回收机制的了解及实践。
- PHP中常用的设计模式有哪些?
- 请提供至少三个通过PHP实现的网站性能优化技巧。
- 请解释什么是defer语句,以及它有什么作用?
- 请解释HTTP的基本概念,以及在Golang中如何使用HTTP?
- 聊一下高并发和高性能的区别和联系?
- 请描述在Golang中使用MongoDB时的最佳实践。
- PHP7和PHP5的性能上有什么差别?
- 请解释一下PHP中的MVC模式是如何工作的?
- PHP中如何进行单元测试以及如何在开发过程中保证代码质量?
- 请问PHP中如何实现多线程?
微信收款码
支付宝收款码