Go by Example

Pointers

Taking a value's address, reading or changing it through a pointer, and handling nil.

A pointer stores the address of a value. & takes an address and * reads or changes the value at that address. Go does not support arithmetic on ordinary pointers.

A function can change its caller's value through a pointer. A nil pointer has no value to dereference:

package main
 
import "fmt"
 
func increment(n *int) {
    *n++
}
 
func main() {
    value := 4
    increment(&value)
    fmt.Println(value) // 5
 
    var missing *int
    fmt.Println(missing == nil) // true
}

In production

Dereferencing nil panics. Define whether a pointer parameter may be nil, and validate it when nil is an expected input. Use values for small data that callers should copy; use pointers when mutation or avoiding a large copy is important.

Enjoyed this? Get more software craft delivered to your inbox.