指向一个映射的指针

huangapple go评论91阅读模式
英文:

Pointer to a map

问题

将一些映射定义为:

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

我想要一个指向这些映射地址的变量(以免复制所有变量)。我尝试使用:

valueTo := &valueToSomeType
nameTo := &nameToSomeType

但是在使用valueTo[number]时,显示出以下错误:
internal compiler error: var without type, init: new

如何解决这个问题?

编辑

这个错误是由另一个问题引起的。

英文:

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.

答案1

得分: 179

地图是引用类型,因此它们总是通过引用传递。你不需要一个指针。Go文档

英文:

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

答案2

得分: 53

更具体地说,根据Golang规范

> 切片、映射和通道是引用类型,不需要使用new进行额外的间接分配。
内置函数make接受一个类型T,该类型必须是切片、映射或通道类型,可选择跟随一个特定于类型的表达式列表。
它返回一个类型为T的值(不是*T)。
内存的初始化如初始值部分所述。

然而,关于函数调用,参数总是通过值传递进行传递。
除非映射参数的值是一个指针。

英文:

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.

答案3

得分: 8

@Mue的答案是正确的。

以下是足够验证的简单程序:

package main

import "fmt"

func main() {
    m := make(map[string]string, 10)
    add(m)
    fmt.Println(m["tom"]) // 期望为nil ???
}

func add(m map[string]string) {
    m["tom"] = "voldemort"
}

这个程序的输出是

voldemort

如果将map按值传递,那么在add()函数中对map的添加不会对main方法产生任何影响。但是我们看到了add()方法添加的值。这证实了map的指针被传递给了add()方法。

英文:

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

huangapple
  • 本文由 发表于 2010年5月11日 17:41:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/2809543.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定