Reputation: 8113
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.
Upvotes: 1
Views: 6643
Reputation: 6864
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.
Upvotes: 8