Understand the contract

A pointer holds the address of a value. The & operator obtains an address, and * accesses the value through a pointer. Use a pointer when a function needs to modify a caller-owned value or represent the absence of an optional value with nil. Ordinary Go pointers do not support pointer arithmetic.

Function arguments are always passed by value. Passing a pointer copies the address, allowing both copies to refer to the same object. Passing an int copies the integer instead. This explains mutation without requiring a separate pass-by-reference rule for the language.

Work through the example

The increment function receives *int and stores an updated integer through it. Starting from two, the program prints three. Parentheses around *value make the read and addition easy to see. The nil guard defines a no-op for absent input; another API could return an error instead.

package main

import "fmt"

func increment(value *int) {
    if value == nil { return }
    *value = *value + 1
}

func main() {
    count := 2
    increment(&count)
    fmt.Println(count)
}

Watch this boundary

Dereferencing nil panics. Also, replacing the local pointer with a different address does not replace the caller’s pointer variable, because that pointer was copied. Avoid choosing pointers solely on an assumption that copying is always expensive; start with the mutation and ownership behavior your API needs.

Practice with a changed input

Write a value-only increment function and compare the caller’s result. Then call the pointer version with nil and document whether ignoring absent input fits your application.

References & further reading

Need help with your Go backend?

I work with engineering teams on focused Go and Kubernetes platform engagements, with limited consulting availability.

Explore Go consulting services