使用Go语言中的map,键是字符串,值是指向结构体的指针。

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

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.

huangapple
  • 本文由 发表于 2015年4月26日 01:10:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/29868239.html
匿名

发表评论

匿名网友

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

确定