Pointer to a map

PointersDictionaryGo

Pointers Problem Overview


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 valueTo[number], it shows
internal compiler error: var without type, init: new

How to get it?

Edit

The error was showed by another problem.

Pointers Solutions


Solution 1 - Pointers

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

Solution 2 - Pointers

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.

Solution 3 - Pointers

@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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser316368View Question on Stackoverflow
Solution 1 - PointersthemueView Answer on Stackoverflow
Solution 2 - PointersVonCView Answer on Stackoverflow
Solution 3 - PointerssabbirView Answer on Stackoverflow