英文:
go map, key is string, value is pointer to a struct
问题
在这段Go代码中,键是字符串,值是指向结构体的指针。
在这里使用Country的指针有什么好处?
我能够移除“*”并实现相同的行为吗?
像这样:
var store = map[string]Country
谢谢。
英文:
type Country struct {
Code string
Name string
}
var store = map[string]*Country{}
in this go code piece, key is string, value is pointer to a struct.
What's the benefit to use pointer of Contry here?
Can I remove the "*" and achieve the same behaviour?
Such as:
var store = map[string]Country
Thanks.
答案1
得分: 7
你可以使用指针或值来实现相同的行为。
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) // 输出 "United States"
fmt.Println(store2["country1"].Name) // 输出 "United States"
}
使用指针将在地图中存储结构体的地址,而不是整个结构体的副本。对于像你的示例中的小结构体,这不会有太大的区别。但对于较大的结构体,可能会影响性能。
英文:
You can achieve the same behavior using either pointer or value.
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"
}
Using a pointer will store the address of the struct in the map instead of a copy of the entire struct. With small structs like in your example this won't make much of a difference. With larger structs it might impact performance.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论