在Golang中传递指针给Maps

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

Passing pointers to Maps in Golang

问题

我在创建Go中的指向映射的指针方面遇到了一些问题。请问我是否正确传递了映射参数?它将整数值与结构体配对。

    type symbol_table struct{
                   ---
                   ---
                   ---
    }
    //是否正确调用了映射参数?
func TD(..., symbolMAP *map[int]symbol_table, ...){
    
                   ---
                   ---
                   ---
    }
    func main(){
               symbolMAP:=make(map[int] symbol_table)
               TD(&symbolMAP)
       }
英文:

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)
       }

答案1

得分: 12

是的,你传递的是正确的,尽管不够习惯。正如系统指出的,传递地图本身而不是指向它的指针几乎总是更好的选择。

现在对整个问题进行评论,Rahul,你不应该“稍后回到这个帖子”。这不是使用stackoverflow的方式。你提出的问题相对简单(“请告诉我是否正确传递了地图参数?”),并且你在示例代码中提供了足够的信息,以便得到像我刚刚给出的简单答案。你应该接受一个答案,或者如果你非常后悔提问这个问题,可以完全删除这个问题。

你提到了可能还有其他问题。这是可以的,但它们不在这里,没有理由让这个问题处于未回答的状态。当你准备好新的问题时,将它们作为新的、独立的问题发布。

英文:

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.

答案2

得分: 7

正如评论中已经指出的,不需要传递指向map的指针

map已经是引用类型。对map的更改将从其他变量中观察到。

另请参阅问题/答案:Go - 指向map的指针

英文:

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.

huangapple
  • 本文由 发表于 2013年2月18日 10:57:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/14928826.html
匿名

发表评论

匿名网友

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

确定