The Code Codex
Theme
← Notes / Fundamentals

note · text14 Oct 2024 · 1 min

Pointers

A pointer is a variable that holds the memory address of another value, instead of the value itself.

Memory

points to

x

address 0xc000

value: 42

p

address 0xc008

value: 0xc000

Memory

points to

x

address 0xc000

value: 42

p

address 0xc008

value: 0xc000

In Go
  • &x takes the address of x; *p reads the value at the address.
  • A pointer’s zero value is nil, and reading *p when p == nil crashes the program (panic).
  • There is no pointer arithmetic (as in C), which removes a whole class of bugs.

Go always passes arguments by value (a copy). For a function to change the original, pass a pointer:

func double(n int) { n *= 2 } // changes the copy
func doublePtr(n *int) { *n *= 2 } // changes the original
x := 21
double(x) // x is still 21
doublePtr(&x) // x is now 42

Pointers also avoid copying large structs and allow methods that change the receiver (func (u *User) Rename(...)).

In Java

Java has no explicit pointers, but every object variable is a reference (in practice, a managed pointer). And Java also passes everything by value: what gets passed is a copy of the reference.

void rename(User u) { u.setName("Ana"); } // changes the original object
void replace(User u) { u = new User("Ana"); } // only swaps the local copy of the reference

That is why you can change an object you receive, but you can’t write a swap(a, b) that swaps the caller’s variables. An empty reference is null, the equivalent of Go’s nil.

See also: Pointers in Go and Variables and constants.