Introduction to Pointers

A variable is a named location in memory that stores a value. A pointer is a special kind of variable that stores the memory address of another variable.

Syntax

  • *: Used to define a pointer type.
  • &: The “address-of” operator. It generates a pointer to its operand.
var p *int // p is a pointer to an integer

x := 42
p = &x     // p now stores the memory address of x

Nil Pointers

The zero value of a pointer is nil. This means it doesn’t currently point to any memory address.

var p *int
fmt.Println(p) // <nil>

Visualization

If x is at memory address 0x123, then p stores 0x123. When you use p, you are looking at the location of the data, not the data itself.