Course contentsShow
← Rust
Lesson 208 of 1,9103. Borrowing and ReferencesFree lesson

The Null Pointer Absence

Understand why Rust references are guaranteed to be non-null at compile time.

In this lesson, you will learn why Rust guarantees that a reference will never be null, effectively eliminating one of the most common sources of software crashes.

The Problem with "Nothing"

In many other programming languages, a pointer (or reference) can hold two kinds of values: an address pointing to actual data, or a "null" value (often represented as 0 or null) that points to absolutely nothing. If your code accidentally tries to read from that empty address, the program crashes immediately—this is the infamous "billion-dollar mistake."

How Rust Eliminates Nulls

In Rust, the rules of Ownership and Borrowing act as a gatekeeper. When you create a reference to a variable, such as let y = &x;, the compiler enforces a strict contract: a reference must point to a valid, initialized piece of memory.

Think of a Rust reference like a physical tag tied to an object. To create the tag, the object must already exist. Because the compiler tracks the Scope-Based Resource Management and Lifetimes of every variable, it prevents you from creating a reference to "nothing." If a value doesn't exist, you simply cannot have a reference to it.

The Compiler as a Guard

Consider this attempt to create a "null" reference:

let my_val = 10;
let reference = &my_val; // This is safe and valid.

If you tried to assign "nothing" to a reference, the compiler would stop you:

let reference = &; // Error: expected expression

You cannot create a reference to an uninitialized variable, and you cannot nullify a reference once it is created. The compiler verifies that every reference is "live" and points to a valid memory location throughout its entire lifetime. If a function asks for a reference, you are mathematically and logically required to provide a valid, existing object. By treating "the absence of a value" as a completely different concept (which we handle using types like Option, rather than null pointers), Rust ensures that your references are always pointing to something real.

Key Takeaway: Because Rust requires that a reference must always point to a valid, initialized piece of memory, "null" pointers cannot exist, ensuring your code will never crash by dereferencing nothing.