Passing pointers to Maps in Golang

13,078

Solution 1

Yes, you are passing it correctly, although not idiomatically. As the system pointed out, passing the map itself rather than a pointer to it is almost always better.

A comment on the question as a whole now, Rahul, you should not "get back to this post later." That is not the way to use stackoverflow. The question you asked was relatively simple ("Can you please let me know if I am passing the map parameter correctly?") and you provided enough information with your sample code to allow a simple answer such as the one I just gave. You should accept an answer, or, if you horribly regret asking your question, delete the question entirely.

You alluded to other questions you might have. This is fine, but they are not here and there is no reason to leave this question in an unanswered state. When you have composed your new questions, post them as new and separate questions.

Solution 2

As already noted in the comments, there is no need to pass pointer to a map.

A map is already a reference type. Changes in the map will be observed from other variables.

See also Q/A: Go - Pointer to map.

Share:
13,078
progfan
Author by

progfan

I am a Software Development Engineer. My present job involves significant amounts of Python, and little Java and Ruby. Ruby is my favourite language and one that I am most proficient in. I also have a fair bit of experience in JavaScript. I love C++, too.

Updated on July 24, 2022

Comments

  • progfan
    progfan almost 2 years

    I am having a little trouble creating pointers to maps in Go. Can you please let me know if I am passing the map parameter correctly? It pairs integer values with structs.

        type symbol_table struct{
                       ---
                       ---
                       ---
        }
        //is the map parameter being called correctly?
    func TD(..., symbolMAP *map[int]symbol_table, ...){
    
                       ---
                       ---
                       ---
        }
        func main(){
                   symbolMAP:=make(map[int] symbol_table)
                   TD(&symbolMAP)
           }
    
  • progfan
    progfan about 11 years
    Thank you for your response. I shall keep your pointers in mind!
  • Charlie Parker
    Charlie Parker about 10 years
    why is better to pass the map itself better? The map I have is a state in a struct and it's important that it gets updated, but I want to be able to choose which map I pass, so passing a pointer to the map that I want to update is important.
  • MrMesees
    MrMesees over 3 years
    You tell someone they are not doing something idiomatically, but fail to give an example of what that would look like. Most of the "answer" is a rant demanding it be accepted despite no code being present.