Home > Mobile >  Go pointer dereferencing
Go pointer dereferencing

Time:10-21

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?

CodePudding user response:

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.

  • Related