Pointer to a map

后端 未结 3 678
予麋鹿
予麋鹿 2020-12-24 01:47

Having some maps defined as:

var valueToSomeType = map[uint8]someType{...}
var nameToSomeType = map[string]someType{...}

I would want a var

相关标签:
3条回答
  • 2020-12-24 02:10

    @Mue 's answer is correct.

    Following simple program is enough to validate:

    package main
    
    import "fmt"
    
    func main() {
        m := make(map[string]string, 10)
        add(m)
        fmt.Println(m["tom"]) // expect nil ???
    }
    
    func add(m map[string]string) {
        m["tom"] = "voldemort"
    }
    

    The output of this program is

    voldemort
    

    Tf the map was passed by value, then addition to the map in the function add() would not have any effect in the main method. But we see the value added by the method add(). This verifies that the map's pointer is passed to the add() method.

    0 讨论(0)
  • 2020-12-24 02:26

    Maps are reference types, so they are always passed by reference. You don't need a pointer. Go Doc

    0 讨论(0)
  • 2020-12-24 02:31

    More specifically, from the Golang Specs:

    Slices, maps and channels are reference types that do not require the extra indirection of an allocation with new.
    The built-in function make takes a type T, which must be a slice, map or channel type, optionally followed by a type-specific list of expressions.
    It returns a value of type T (not *T).
    The memory is initialized as described in the section on initial values

    However, regarding function calls, the parameters are passed by value (always).
    Except the value of a map parameter is a pointer.

    0 讨论(0)
提交回复
热议问题