user2989731
user2989731

Reputation: 1359

What does the '*' and '&' symbol in Go mean?

I'm having trouble understanding the * and & symbols in Go. I understand the concept that pointer receivers allow us to modify the value that a receiver points to:

type Vertex struct {
    X, Y float64
}

// This adjust the value of v.X and v.Y
func (v *Vertex) Scale(f float64) {
    v.X = v.X * f
    v.Y = v.Y * f
}

But I also see functions returning the a pointer receiver, for example the net/http library.

func NewRequest(method, url string, body io.Reader) (*Request, error)

In this scenario, why is there a star in front of the Request being returned?

Additionally, I often see & used when assigning variables

import net/http
client := &http.Client{}

Why not just client := http.Client{}?

Upvotes: 7

Views: 14712

Answers (1)

L.S.
L.S.

Reputation: 506

Have a look here: https://tour.golang.org/moretypes/1

Go uses pointers like C or C++. The * symbol is used to declare a pointer and to dereference. The & symbol points to the address of the stored value.

Compared to C/C++, however, the pointer in Go is declared with the * preceding the type rather than following it.

You can read more about pointers in general here: https://en.wikipedia.org/wiki/Pointer_(computer_programming)

In your example they are used to pass the address of the instance of the object instead of copying the instance. This is more efficient and you don't have the problem that you have 2 copies objects, because you only need one in this case and would need to destroy one of them.

This is because the instance of the Object is at a specific address in memory and if you want to refer exactly to that object, you have to pass the address instead of the object itself.

Some other languages like Java have internal ways to hide the pointer problems from the user or don't use them at all. They often need a garbage collector in that case. Go however lets the user decide to use pointer (though it also has a garbage collector).

Upvotes: 15

Related Questions