惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
GbyAI
GbyAI
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
Last Week in AI
Last Week in AI
V
Visual Studio Blog
酷 壳 – CoolShell
酷 壳 – CoolShell
The Cloudflare Blog
博客园 - 【当耐特】
博客园 - 叶小钗
量子位
博客园 - 聂微东
S
SegmentFault 最新的问题
美团技术团队
Hugging Face - Blog
Hugging Face - Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
月光博客
月光博客
宝玉的分享
宝玉的分享
小众软件
小众软件
罗磊的独立博客
有赞技术团队
有赞技术团队
Stack Overflow Blog
Stack Overflow Blog

NickChenyx's Blog

Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish Create_Rubbish
Create_Rubbish
nickChen · 2018-04-18 · via NickChenyx's Blog

漫谈 Golang 之 map

Created At :

Count:386 Views 👀 :

  1. map 参数传递
  2. 无法对 map value 取地址

map 参数传递

当 map 作为参数被传递时,实际上传递的 map 的指针信息,传递后的修改会同步到函数外。

可以看到 m 被传递到了 onMap 函数中,但是最后在函数外的 m 也是被修改了的。

package main
import "fmt"
func main() {
    m := map[int]int{}
    opMap(m)
    printMap(m)
}
func opMap(m map[int]int) {
    for i := 0; i < 10; i++ {
        m[i] = i
        printMap(m)
    }
}
func printMap(m map[int]int) {
    fmt.Printf("len: %v, map: %v\n", len(m), m)
}
// Output:
// len: 1, map: map[0:0]
// len: 2, map: map[0:0 1:1]
// len: 3, map: map[0:0 1:1 2:2]
// len: 4, map: map[0:0 1:1 2:2 3:3]
// len: 5, map: map[0:0 1:1 2:2 3:3 4:4]
// len: 6, map: map[0:0 1:1 2:2 3:3 4:4 5:5]
// len: 7, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6]
// len: 8, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7]
// len: 9, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8]
// len: 10, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8 9:9]
// len: 10, map: map[0:0 1:1 2:2 3:3 4:4 5:5 6:6 7:7 8:8 9:9]

无法对 map value 取地址

如下的代码中,尝试获取 map value 的地址,会在编译时显示失败。

Why Go forbid taking the address of map member

package main
import "fmt"
func main() {
    m := map[int]int{}
    address := &m[0] // invalid operation: cannot take address of m[0] (map index expression of type int)
    fmt.Println(address)
}

转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 nickchenyx@gmail.com

Title:漫谈 Golang 之 map

Count:386

Author:nickChen

Created At:2022-07-23, 20:59:01

Updated At:2023-05-08, 23:27:10

Url:http://nickchenyx.github.io/2022/07/23/golang-map-dive-into/

Copyright: 'Attribution-non-commercial-shared in the same way 4.0' Reprint please keep the original link and author.