2010-05-11 22 views
32

有一些地圖定義爲:指向一個地圖

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

我想指向地圖的地址的變量(以不復制所有變量)。我試了一下使用:

valueTo := &valueToSomeType 
nameTo := &nameToSomeType 

,但在使用valueTo[number],它顯示了
內部編譯器錯誤:VAR無類型時,init:新

如何獲得呢?

編輯

錯誤是由另外一個問題顯示。

回答

73

地圖是引用類型,所以它們都是通過引用傳遞的。你不需要一個指針。

+1

看看這裏:https://dave.cheney.net/2017/04/29/there-is-no-pass-by-reference-in-go – Joppe 2017-04-30 08:50:04

+0

是的,戴夫描述它更好。閱讀他的博客條目。 – Mue 2017-05-01 15:12:02

37

更具體地,從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

然而,關於function calls,所述參數由值(總是)通過
除了map參數的值是一個指針。

+0

那麼誰是對的? – 2014-04-15 21:16:37

+2

@JuliusF兩者,但我的回答更精確:指針是按值傳遞的。更多關於「通過價值傳遞」http://stackoverflow.com/a/23046811/6309。 – VonC 2014-04-15 21:18:39