Go指针解引用

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

Go pointer dereferencing

问题

我目前正在尝试学习GO语言,主要了解和使用Java、ASP.Net和一些Python,没有使用C语言指针的经验,这导致我目前感到困惑。

我目前正在使用一个名为Commando的库来编写我的第一个GO项目。
在这个库中,我有一个名为CommandRegistry的结构体,我感兴趣的变量叫做Commands。

在结构体中,该变量的描述如下:

// registered command configurations
Commands map[string]*Command

初看之下,我会理解这个变量是一个包含字符串列表的Map对象,但它还显示了指向实际Command对象的指针引用。

我能看到的只是一个我可以遍历的Map,它返回命令的名称(字符串),
然而,我想知道类型描述中的*Command是否意味着我可以以某种方式取消引用指针并提取对象本身的附加信息。

据我所知,&操作符用于创建另一个对象的新指针。基本上是按引用传递而不是按值传递
*操作符通常表示对象是一个指针,或者用于在新函数中要求一个指针。

是否有办法可以检索Command对象,或者为什么类型中包含*Command的声明?

英文:

I'm currently trying to learn GO and mainly knowing and working with Java, ASP.Net and some Python, there is no experience working with C-like pointers, which causes my current confusion.

A library I'm currently using to write my first GO project is called Commando.
There I have the struct CommandRegistry and the variable of interest is called Commands.

In the struct the variable is described as the following:

// registered command configurations
Commands map[string]*Command

On a first glimpse I would understand this as a Map object containing a list of Strings, however it also shows the pointer reference to the actual Command object.

All I can see is that it is a map I can loop over which returns the name of the command ( the string ),
however I'm wondering if the *Command in the type description means I can somehow dereference the pointer and retrieve the object itself to extract the additional information of it.

As I know the & operand is used to create a new pointer of another object. Pass-by-reference basically instead of pass-by-value.
And the * operand generally signals the object is a pointer or used to require a pointer in a new function.

Is there a way I can retrieve the Command object or why does the type contain the *Command in it's declaration?

答案1

得分: 2

Commands 是一个以字符串为键、指向 Commands 的指针为值的映射(字典)。通过传递一个键,你将获得指向对应命令的指针。然后,你可以使用 * 运算符将指针解引用为实际的 Command 对象。类似于 dereferencedCommand := *Commands["key"]

* 运算符可能会相当令人困惑,至少对我来说是这样。当作为类型使用时,它表示我们正在接收某个变量的内存地址。但是要将内存地址解引用为具体类型,你也需要使用 * 运算符。

英文:

Commands is a map (dictionary) which has strings as keys, and pointers to Commands as values. By passing it a key, you will get a pointer to the command it belongs to. You can then dereference the pointer to an actual Command object by using the * operator. Something like dereferencedCommand := *Commands["key"].

The * operator can be quite confusing, at least it was for me. When used as a type it denotes that we are receiving the memory address of some variable. But to dereference a memory address to a concrete type, you also use the * operator.

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

发表评论

匿名网友

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

确定