美文网首页
There is no pass-by-reference in

There is no pass-by-reference in

作者: allenhaozi | 来源:发表于2020-07-08 19:03 被阅读0次

背景

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

相关文章

网友评论

      本文标题:There is no pass-by-reference in

      本文链接:https://www.haomeiwen.com/subject/kythcktx.html