W3Basic Logo

Go Pointers

A pointer is a variable that is used to store the memory address of another variable as its value. Pointers in Golang is also termed as the special variables. Unlike C, Go has no pointer arithmetic.


To understand pointers, we need to understand how memory works in Go (and in most other programming languages). The memory is divided into cells that can store a single value and that can be accessed by their address.

+------------+------------+------------+------------+------------+
| 45         | "Hello"    | 3.14       | true       | 0          |
+------------+------------+------------+------------+------------+
| 0x00000001 | 0x00000002 | 0x00000003 | 0x00000004 | 0x00000005 |
+------------+------------+------------+------------+------------+

In the simplified example above, we have 5 cells in memory, each one storing a value of a different type. The first cell stores the integer 45, the second cell stores the string "Hello", etc.

Getting the address of a variable in Go

In Go, we can get the address of a variable using the & operator. For example, if we want to get the address of the variable x, we can write &x. The type of the result is *T where T is the type of the variable.

package main

import "fmt"

func main() {
	x := 5
	address := &x
	fmt.Println(address)
}

The variable address is a pointer to the variable x.

Getting the value of a pointer in Go

The reverse operation of getting the address of a variable is getting the value of a pointer. We can do this using the * operator.

package main

import "fmt"

func main() {
	x := 5
	address := &x
	value := *address
	fmt.Println(value)
}

Passing a pointer to a function

To make a function able to modify a variable, we need to pass a pointer to the variable. We can do this by using the * operator in the function signature.

package main

import "fmt"

func setToZero(x *int) {
	*x = 0
}

func main() {
	x := 5
	setToZero(&x)
	fmt.Println(x)
}

Indeed, when calling a function, a copy of the arguments is created. So if we pass a variable to a function, the function will only be able to modify the copy of the variable, not the original variable. But the copy of an address gives us exactly the same information as the original address. As an analogy, if you copy by hand the business card of a person, you still have all the information you need to contact that person. This is how we can modify a variable from a function.

© 2023 W3Basic. All rights reserved.

Follow Us: