Go by Example

Pointers

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

A pointer is a value that stores the address, or location in memory, of another value. & gets that address and * reads or changes the value there. Go does not let ordinary pointers be used for arithmetic.

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

Trying to read through a nil pointer, one that has no address, causes a panic, an unexpected failure that stops normal execution. Decide whether a pointer input may be nil and check it when that is allowed. Use a value when callers should get a copy; use a pointer when a function must change the caller's value.

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