๐ŸŽ“ A1Learner
๐Ÿ”

Go Pointers

A pointer is a value that holds the address of another value. Reading through a pointer reaches the value stored at that address.

Read Through a Pointer

The & sign takes the address of x. The pointer p holds that address, and *p reads the value there.

package main

import "fmt"

func main() {
	x := 10
	p := &x
	fmt.Println(*p)
}

Change Through a Pointer

Writing through *p changes the value at the address. The variable x then holds the new value.

package main

import "fmt"

func main() {
	x := 10
	p := &x
	*p = 20
	fmt.Println(x)
}

A Pointer Parameter

The function double takes a *int parameter. It doubles the value at that address.

package main

import "fmt"

func double(n *int) {
	*n = *n * 2
}

func main() {
	x := 21
	double(&x)
	fmt.Println(x)
}

Check a Nil Pointer

A pointer with no value behind it is nil. The check runs before any read through p.

package main

import "fmt"

func main() {
	var p *int
	if p == nil {
		fmt.Println("no value")
	} else {
		fmt.Println(*p)
	}
}

Example

package main

import "fmt"

func swap(a *int, b *int) {
	temp := *a
	*a = *b
	*b = temp
}

func main() {
	x := 3
	y := 7
	swap(&x, &y)
	fmt.Println(x, y)
}

Key points

  • Pointer: a value that holds the address of another value.
  • Use & to take the address of a value.
  • Use * before a pointer to read or change the value it points to.
  • A pointer type is written with a star, like *int for a pointer to an int.
  • The zero value of a pointer is nil, which points to nothing.
  • Check a pointer against nil before reading through it.

In this example, swap receives the addresses of x and y. The value at a is saved in temp first. The value at b is then written into a. The saved value is written into b last. Main prints x and y in their swapped order.

Note

Addresses can be stored and followed, but they cannot be moved with maths.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Go Playground

Exercise

x holds 10 and p := &x runs. What does *p = 30 do?