Pointers

Pointers

Now fasten your seatbelts, we talk about one of the concepts, which make people think go is complicated.

Pointers simply explained

You go to a theatre. There you hand in your coat at the cloakroom. You get a receipt saying “your coat is on hook 42”.

Now the receipt is a pointer to the coat. You can make a copy of the receipt, but there is still only one coat.

That’s all there is to it!

Why pointers?

Pointers are all about efficiency. A pointer to a complex data structure is faster to handle than to copy the structure.

Pointers in Action

  6         coat := "I am a coat"
  7         receipt := &coat
  8
  9         receipt2 := &coat
 10
 11         fmt.Println(*receipt)
 12         fmt.Println(*receipt2)

With this code you will get this output:

I am a coat
I am a coat

This is because receipt and receipt2 pointing to the same coat.

The operator & means “give me the address of the variable”. So this is de-referecing. The memory address ist the place where the data is stored.

The operator * means tread this as a pointer. So *receipt fetches the address stored in receipt and uses the content which is stored there.

If you just do:

fmt.Println(receipt)

you will get number like 0xc000010230, which is the memory address.

Pointing to different variables

 14         var anotherCoat string
 15         anotherCoat = "I am the red coat"
 16
 17         var redReceipt *string
 18         redReceipt = &anotherCoat
 19         fmt.Println(*redReceipt)
 20
 21         redReceipt = &coat
 22         fmt.Println(*redReceipt)

A string pointer can reference different strings in the lifetime. In line 18 redReceipt gets the address from anotherCoat. After that in line 21 its gets the address of coat.

So the output is:

I am the red coat
I am a coat

Because in line 19 the red coat is referenced and in line 22 the coat.

Source

See the full source on github.

Sources