Learnmonkey Learnmonkey Logo

Go Pointers

What is a Pointer?

Pointers are variables that point to the memory address of another variable. The "memory" we are talking about here is the physical memory of the computer (i.e. hard drive). Pointers can also be found in C and C++.

Why use Pointers?

We can use pointers if we want to physically change the variables we want to pass into our function. However, it's usually best to use normal variables over pointers.

Making a Pointer

Below is the general format of making a pointer:


var variable-name *data-type
    

variable-name is the name of the pointer variable we want to make. data-type is the data type of the variable in the memory address we are referencing.

Getting the Address of a Variable

To get the address of a variable in Go, we put the ampersand symbol (&) before the variable. For example:


var x int = 5
fmt.Println(&x)
    

The above code returns a hexadecimal number for the address of where the variable x is stored in memory:

0xc000016190

We can also set the address to a pointer variable:


var y int = 10
var y_addr *int
y_addr = &y
    

Getting the Data at a Memory Address

To get the data at the address, we use an asterisk (*) yet again. If we type *x, we are referring to the value stored at the piece of memory that the x variable is pointing to.

For example:


package main
import "fmt"

func main() {
    var myInt = 5 // declare an integer variable called myInt
    var myPtr *int = &x // declare a pointer variable that points to the memory location of myInt
    fmt.Println(*myPtr) // get the data stored at the memory address myPtr is pointing to
}
    

The above code returns:

5