Learn about pointers and memory addresses in Go. Some things are more easily done with pointers, others without. Eitherway pointers are fun to work with!

Not all programming languages support pointers, typically they are found in low level languages like C or C++. Go also supports them.

Examples

Memory addresses

Every variable is is stored in the memory and has a unique address. This can be accessed with the ampersand (&) operator.

1
2
3
4
5
6
7
8
9
package main                                                                                                              

import "fmt"

func main() {
var x int = 5
fmt.Printf("Address of variable x: %x\n", &x )
fmt.Printf("Value of variable x: %d\n", x )
}

If you run the code with the command

1
go run program.go

You will see the program tells you the memory address and the contents in that memory address.

Something like:

1
2
Address of variable x: c4200160d8
Value of variable x: 5

The memory address will be different on your computer, value the same.

Pointers

A pointer is a variable whose address is the direct memory address of another variable.

The asterisk * is used to declare a pointer.
The form is:

1
var var_name *var-type

You have to write the variable type,

1
2
3
4
5
/* pointer to an integer */
var ipointer *int

/* pointer to a float */
var fpointer *float32

So lets see that in an example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package main                                                                                                              

import "fmt"

func main() {
// variable
var x int = 5

// create pointer
var ipointer *int

// store the address of x in pointer variable
ipointer = &x

// display info
fmt.Printf("Memory address of variable x: %x\n", &x )
fmt.Printf("Memory address stored in ipointer variable: %x\n", ipointer )
fmt.Printf("Contents of *ipointer variable: %d\n", *ipointer )
}

This will output something like:

1
2
3
Memory address of variable x: c4200160d8
Memory address stored in ipointer variable: c4200160d8
Contents of *ipointer variable: 5