1
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
  • 1
    I'm not knowledgeable on go specifically, but my immediate thought is that this would make rebalancing the map (if necessary) a more costly operation (would require moving more memory). Getting and setting data would also become more costly for the same reason (requires copying the full struct, instead of a pointer to the struct) Commented Apr 25, 2015 at 17:20

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

In particular, with a small struct like this, not using a pointer will perform better. As always, if/when performance is a concern, don't guess, benchmark.
Only caveat is that you can't directly assign to the value without a pointer (store2["country1"].Name = "X").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.