Golang pointers

What is pointer?

Programs store values in memory, and each memory block (or word) has an address, which is usually represented as a hexadecimal number, like 0x6b0722 or 0xf84202d7f1.

Pointer is a special type that holds the address of a variable.

In the above example, variable b has value 157 and is stored at memory address 0x1240a124.

The variable a holds the address of b. Now a is said to point to b.

How to create and use pointer

This address can be stored in a special data type called a pointer.

In the above case, it is a pointer to an int.So i1 is denoted by *int. If we call that pointer intP, we can declare it as:

Go has the address-of operator &, which, when placed before a variable, gives us the memory address of that variable.

Dereferencing a pointer

Dereferencing a pointer means accessing the value of the variable to which the pointer points.
*a is the syntax to deference a.

What you can’t do with golang pointers

Go has the concept of pointers like most other low level languages – C, C++.

But it’s not allowed to do calculations with pointers.

This often lead to erroneous memory access in C or C++ and thus fatal crashes of programs.

This restrictions with pointers in Go makes the language memory-safe.


About Paul Smith

GoLang / PHP developer with more than 10 years experience in IT.