2015-04-25 35 views
0
type Country struct { 
    Code string 
    Name string 
} 

var store = map[string]*Country{} 

在這個go代碼片中,鍵是字符串,值是指向結構體的指針。 這裏使用Contry的指針有什麼好處? 我可以刪除「*」並獲得相同的行爲嗎? 如:走圖,鍵是字符串,值是指向結構的指針

var store = map[string]Country 

謝謝。

+1

我並沒有專門的知識,但我的直接想法是,這將使平衡地圖(如果有必要)成本更高的操作(需要移動更多內存)。由於相同的原因,獲取和設置數據也會變得更加昂貴(需要複製完整的結構,而不是指向結構的指針) – Dave

回答

1

您可以使用指針或值實現相同的行爲。

package main 

import (
    "fmt" 
) 

type Country struct { 
    Code string 
    Name string 
} 

func main() { 
    var store = make(map[string]*Country) 
    var store2 = make(map[string]Country) 

    c1 := Country{"US", "United States"} 

    store["country1"] = &c1 
    store2["country1"] = c1 

    fmt.Println(store["country1"].Name) // prints "United States" 
    fmt.Println(store2["country1"].Name) // prints "United States" 

} 

使用指針將結構的地址存儲在映射中,而不是整個結構的副本。對於你的例子中的小結構來說,這並沒有太大的區別。如果結構較大,則可能會影響性能。

+1

特別是,使用像這樣的小結構,*不使用指針會更好。與往常一樣,如果/當表現是一個問題時,不要猜測,基準。 –

+0

唯一需要注意的是,如果沒有指針('store2 [「country1」] .Name =「X」'),你不能直接賦值。 – OneOfOne