AnyCompiler

Pointers

A pointer holds the memory address of a value. & takes the address of a variable, and * dereferences a pointer to get (or set) the value it points to. Unlike Rust, Go has no ownership or borrowing rules to satisfy — pointers are just a direct way to share and mutate a value.

package main

import "fmt"

func main() {
	count := 10
	pointer := &count

	fmt.Println(*pointer)
	*pointer = 20
	fmt.Println(count)
}
Output
10
20

Passing a pointer into a function

Go passes arguments by value by default — a function normally gets its own copy. Passing a pointer instead lets a function modify the caller's actual variable, which is how double below changes value in main even though value itself was never reassigned there.

package main

import "fmt"

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

func main() {
	value := 21
	double(&value)
	fmt.Println(value)
}
Output
42

Next: error handling — Go's explicit if err != nil pattern instead of exceptions.

Practice exercise

Write a function increment(n *int) that adds 1 to the value n points to. Call it with a pointer to a variable count := 5, then print count.