HiveBrain v1.2.0
Get Started
← Back to all entries
patterngoCritical

What is the meaning of '*' and '&'?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
meaningandwhatthe

Problem

I am doing the http://tour.golang.org/. Could anyone explain this function to me, specifically lines 1, 3, 5, and 7? I am particularly curious about what the '*' and '&' symbols do. What are they supposed to do when mentioned in a function declaration?
A toy example:
` 1: func intial1(var1 int, var2 int, func1.newfunc[]) *callproperfunction {
2:
3: addition:= make ([] add1, var1)
4: for i:=1;i

It seems that they are pointers, similar to what we have in C++. However, I am having trouble connecting these concepts to what we have here. In other words, what do '*' and '&' do when used in a function declaration in Go?

I understand what reference and dereference mean. What I cannot understand is how we can use a pointer to a function in Go. For example, in lines 1 and 7, what do these two lines do? Is the function named initial1 declared to return a pointer? And in line 7, are we calling it with arguments using the returned function?

Solution

This is possibly one of the most confusing things in Go. There are basically 3 cases you need to understand:

The & Operator

& goes in front of a variable when you want to get that variable's memory address.

The * Operator

goes in front of a variable that holds a memory address and resolves it (it is therefore the counterpart to the & operator). It goes and gets the thing that the pointer was pointing at, e.g. myString.

myString := "Hi"
fmt.Println(*&myString)  // prints "Hi"


or more usefully, something like

myStructPointer = &myStruct
// ...
(*myStructPointer).someAttribute = "New Value"


* in front of a Type

When is put in front of a type, e.g. string, it becomes part of the type declaration, so you can say "this variable holds a pointer to a string". For example:

var str_pointer *string


So the confusing thing is that the * really gets used for 2 separate (albeit related) things. The star can be an operator or part of a type.

Code Snippets

myString := "Hi"
fmt.Println(*&myString)  // prints "Hi"
myStructPointer = &myStruct
// ...
(*myStructPointer).someAttribute = "New Value"
var str_pointer *string

Context

Stack Overflow Q#38172661, score: 288

Revisions (0)

No revisions yet.