Skip to content
Theory · Enums and match · lesson 2 of 8

Option instead of null

In the previous lesson every item held something. But sometimes there is nothing to hold.

Picture a gift box with an honest sticker. It says either "a number inside" or "empty". Before you reach for the gift, you read the sticker and do not put your hand into an empty box.

Now a programming task. A function divides one number by another, but you cannot divide by zero. What does it return for 1 / 0? In many languages such cases return a special value: null, -1 or 0. The calling code may forget to check it, and the error surfaces far from where it appeared.

Tony Hoare, who invented null, called it his "billion-dollar mistake". Rust has no null at all, and a missing value shows right in the type:

Rust
fn divide(a: i32, b: i32) -> Option<i32> {
    if b == 0 { None } else { Some(a / b) }
}

fn main() {
    let half = divide(10, 2);
    let bad = divide(1, 0);
    println!("{:?} {:?}", half, bad); // Some(5) None
}

Let's walk through the example line by line:

  1. -> Option<i32> promises that the function returns a box holding either an i32 or nothing.
  2. When b == 0, the function returns None, an empty box.
  3. Otherwise it returns Some(a / b), a box with the quotient inside.
  4. {:?} prints both boxes along with their stickers: Some(5) None.

Option is an ordinary enum

Option is an enum from the standard library with two variants: Some with a value inside and None with no data. In Option<T>, the T is replaced by the type of the contents: Option<i32> is a box for a number, Option<String> a box for a string.

Unlike Parcel from the previous lesson, Option and its variants are available in every file without the type name. So you write Some(5) and None, not Option::Some(5).

You print an Option only with {:?}. The {} format is not defined for it, since it is unclear what to print in place of an empty box.

Option<i32> is not an i32

A box with a number is not a number yet. Let's try adding one to the result of a division:

Rust
let half = divide(10, 2);
let next = half + 1; // ✗
TEXT
error[E0369]: cannot add `{integer}` to `Option<i32>`

The program does not compile. half has the type Option<i32>, and + is not defined between an Option and a number. Rust does not look inside the box on its own, even when it holds Some(5). This is a build error, not a panic: the program will not run until you handle both cases.

That is the protection. In a language with null, half + 1 would compile and crash on an empty value. In Rust the compiler does not let you work with the contents until you open the box.

Interviewers like to ask this: "How does Rust manage without null?" The answer:

  • a value that may be missing has the type Option<T>: Some(v) or None;
  • a plain T is always there, and you do not need to check it;
  • Option<i32> is a different type from i32, so you must handle None before use;
  • errors that other languages hit at run time are found here by the compiler.

How to open the box

You get the value out by checking the variant. The same match that sorted the items takes an Option apart too:

Rust
match divide(7, 0) {
    Some(q) => println!("{q}"),
    None => println!("no result"), // no result
}
  1. divide(7, 0) returns None.
  2. The line Some(q) would fit a full box and put the quotient into q.
  3. The box is empty, so the line None runs and prints no result.

Here the gift picture falls short. An empty gift box fits anything. But None always knows its type: an empty Option<i32> is an empty box for a number specifically, and you cannot put a string into it.

Common mistake

An Option is printed with {}, like a plain number:

Rust
let half = divide(10, 2);
println!("{}", half); // ✗
TEXT
error[E0277]: `Option<i32>` doesn't implement `std::fmt::Display`

The program does not compile: {} can print numbers and strings, but not an Option. The fix is {:?}, which prints Some(5). And to print the number 5 itself, you first take it out with match.

Key points

  • Option<T> is an enum with the variants Some(value) and None; Rust has no null.
  • Some(5) has the type Option<i32>, not i32: you cannot apply + to it (E0369).
  • You print an Option with {:?}: you get Some(5) or None.
  • You get the value out by checking the variant, for example with a match that has the lines Some(q) and None.