开发者

Pointer to a map

Having some maps defined as:

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

I would want a variable that points to the address of the maps (to don't copy all variable). I tried it using:

valueTo := &valueToSomeType
nameTo := &nameToSomeType

but at using va开发者_运维知识库lueTo[number], it shows

internal compiler error: var without type, init: new

How to get it?

Edit

The error was showed by another problem.


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


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.


@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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜