[英]go map, key is string, value is pointer to a struct
type Country struct {
Code string
Name string
}
var store = map[string]*Country{}
在此go代碼段中,鍵是字符串,值是指向結構的指針。 在這里使用Contry的指針有什么好處? 我可以刪除“ *”並實現相同的行為嗎? 如:
var store = map[string]Country
謝謝。
您可以使用指針或值來實現相同的行為。
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"
}
使用指針會將結構的地址存儲在映射中,而不是整個結構的副本。 對於您的示例中的小結構,這沒有多大區別。 使用較大的結構可能會影響性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.