There is no pass-by-reference in Go (map)

allenhaozi · · 478 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

背景

go map的类型算不算真正意义的引用

go 官方的说明

Map types are reference types, like pointers or slices, and so the value of m above is nil; it doesn't point to an initialized map. A nil map behaves like an empty map when reading, but attempts to write to a nil map will cause a runtime panic; don't do that. To initialize a map, use the built in make function:
The make function allocates and initializes a hash map data structure and returns a map value that points to it. The specifics of that data structure are an implementation detail of the runtime and are not specified by the language itself. In this article we will focus on the use of maps, not their implementation.

看下面这段代码

package main

import "fmt"

func fn(m map[int]int) {
    m = make(map[int]int)
}

func main() {
    var m map[int]int
    fn(m)
    fmt.Println(m == nil) // got true, hope false
}

这段代码说明map是reference type是有前提的, 那么就是它必须被初始化

那么go map是什么类型

A map value is a pointer to a runtime.hmap structure.

通过下面方法初始化一个map的时候

m := make(map[int]int)

编译器会调用 runtime.makemap, 方法

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

方法 runtime.makemap 返回了一个指向 runtime.hmap struct 的指针

https://blog.golang.org/maps
https://dave.cheney.net/2017/04/29/there-is-no-pass-by-reference-in-go
https://stackoverflow.com/questions/40680981/are-maps-passed-by-value-or-by-reference-in-go


有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:allenhaozi

查看原文:There is no pass-by-reference in Go (map)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

478 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传