经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » Go语言 » 查看文章
golang中,map作为函数参数是如何传递的
来源:cnblogs  作者:idea偶买噶  时间:2019/6/3 9:02:41  对本文有异议

当你声明一个map的时候:

  1. m := make(map[int]int)

编译器会调用 runtime.makemap

  1. // makemap implements a Go map creation make(map[k]v, hint)
  2. // If the compiler has determined that the map or the first bucket
  3. // can be created on the stack, h and/or bucket may be non-nil.
  4. // If h != nil, the map can be created directly in h.
  5. // If bucket != nil, bucket can be used as the first bucket.
  6. func makemap(t *maptype, hint int64, h *hmap, bucket unsafe.Pointer) *hmap

所以实际上是返回一个hmap的指针。

如何验证呢?

  1. func main(){
  2. m := make(map[int]int)
  3. m[1] = 1
  4. fmt.Printf("原始map的内存地址是:%p\n", m)
  5. modify(m)
  6. fmt.Println("map值被修改了,新值为:", m)
  7. }
  8. func modify(m interface{}){
  9. fmt.Printf("函数里接收到map的内存地址是:%p\n", p)
  10. m := p.(map[int]int)
  11. m[1] = 2
  12. }

输出结果:

  1. 原始map的内存地址是:0xc00009e030
  2. 函数里接收到map的内存地址是:0xc00009e030
  3. map值被修改了,新值为: map[1:2]

在main函数中,m是个指针变量,它保存的值是:0xc00009e030。

在modify函数中,m也是个指针变量,保存的值也是:0xc00009e030。

说明初始化map后,返回的是指针变量,在函数之间,传递的是map的地址。

map和channel是相似的。

那么为什么不是 *map[key]value呢,这样不是更直观?

Ian Taylor answered this recently in a golang-nuts 原话是:

In the very early days what we call maps now were written as pointers, so you wrote *map[int]int. We moved away from that when we realized that no one ever wrote map without writing \*map.

意思是,一开始也是写作 *map[key]value,后来发现所有的map都是当作指针来用的,于是就省略简写了。

原文链接:http://www.cnblogs.com/zhouj-happy/p/10962500.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号