Intro

A pointer "points" to the memory address of a value rather than the value itself.

Pointers in golang are assigned to variables using & operator. The & operator is the address operator.

Addresses are "dereferenced" with the * operator. Dereferencing a pointer gives you back the value.

The zero value for a pointer is nil

A pointer type is a type that represents a pointer. Pointer types are declared with a * prior to the type.

go
// Create a pointer variable with a nil value
var stuff *str

// Dereference a pointer to access the value.
// Get the address of the stuff variable
&stuff

// Dereference a pointer that is passed to a function
func changePointer(p *int) {
    // Notice the syntax to dereference is altered
    *p = 20
}

Considerations

  • If a nil value pointer is passed to a function the value cannot be reassigned
  • Pointers should be used to modify a variable when a function expects an interface
  • If you try to dereference a nil pointer the program will panic.
# golang