Pointers

A pointer is the address of a value. Copying the argument does not change it. A write through the address does.

In Go everything is passed by value. A function receives a copy of the argument. If the argument is a pointer, the address is copied, and both sides see the same data.

func ApplyBonus(balance *int, bonus int) int {
    if balance == nil {
        return 0
    }
    *balance += bonus
    return *balance
}

*balance is the value at the address. &n is the address of the variable n. The zero pointer equals nil, and dereferencing nil panics. So the check at the start of the function is part of the contract, not extra caution, when nil is meaningful.

A pointer is not needed "for speed" on every int. A copy of an integer is cheaper than a jump through an address, and it is easier to read. A pointer is needed when the function must change the caller's value, when the value is large and you truly mind copying it, or when absence is expressed through nil. For "a number or absence" a pair (int, bool) or a separate type is usually more honest than a bare pointer: nil is easy to forget to check.

Do not take the address of a loop variable, and do not keep a pointer to a slice element if the slice will still grow through append. Growth can move to a new array, and the old pointer will remain on abandoned memory... no, it will keep pointing at the old array, which is no longer the slice. You will change something other than what the caller sees. This is a hard bug. An index is more reliable.

The garbage collector will take a value when no pointers to it remain. You do not free memory by hand. What you do manage are files, connections, and mutexes — the things that are not memory.

Practice

  1. What gets copied

    A function is declared as func bump(n int). The caller passed their own variable. Can bump change it?

    • Yes, arguments in Go are always by reference
    • No, n is a copy
    • Yes, if the variable was declared with var, not with :=
    • Yes, but only if n is greater than zero
  2. A bonus on the balance

    Write ApplyBonus(balance *int, bonus int) int. If balance is nil, return 0. Otherwise add bonus to the value at the pointer and return the new balance. The caller must see the change to their own variable, not only the return value.

  3. Dereferencing nil

    What happens when *p is evaluated, if var p *int and no value was set?

    • You get 0 with no error
    • A panic
    • The code does not compile
    • You get a pointer to a new variable