Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 132 ยท Operators and Control Flow

Option and Handling Absence

Learn Rust's Option type - why Rust has no null, Some and None, match and if let, unwrap and expect, unwrap_or, map, and_then, filter, ok_or and the ? operator.

Sooner or later every program asks a question that might have no answer. Is there a first element in this list? Does this user have a nickname? Can this text be found inside that text? In many languages the "no answer" case is a special value called null (or nil, or None), and forgetting to check for it is one of the most expensive mistakes in programming history. The inventor of null references called it his "billion-dollar mistake".

Rust has no null. Instead, a value that might be missing has its own type, Option<T>, and the compiler will not let you use it as if it were present until you have dealt with the absent case. This lesson explains how Option works, how to read it with match and if let, why unwrap is risky, and which methods let you transform optional values in a few clean lines. It builds directly on patterns and match; Ownership comes next.

What is Option?

Option is an ordinary enum from the standard library, available everywhere without an import:

Rust
enum Option<T> {
    None,
    Some(T),
}

Either there is nothing (None), or there is a value of type T wrapped in Some. The <T> means "any type": Option<i32>, Option<String> and Option<&str> are three different types. (Generics get their own chapter, starting with Generics.)

Rust Creating Option values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Standard library functions return Option whenever "nothing" is a normal outcome: first, get, find, position, pop, parse (well, that one returns a Result, covered later) and many more. Notice that for None you sometimes have to write the type: let nothing: Option<i32> = None;, because None alone does not say what it would have contained.

Why a separate type is safer

The key idea: an Option<i32> is not an i32. You cannot use it where an i32 is expected, and the compiler explains this the moment you try:

Rust Using an Option as a number (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The error says that you cannot multiply Option<&i32> by an integer:

TEXT
error[E0369]: cannot multiply `Option<&{integer}>` by `{integer}`

In a language with null, this bug would compile and then crash (or worse, quietly misbehave) with an empty list. In Rust, the possibility of absence is written in the type, so the question "did I handle the empty case?" is something the compiler asks for you. The whole category of null-pointer errors cannot happen in safe Rust.

Taking an Option apart

match

The most direct way to get the value out is a match. Because Option has two variants, an exhaustive match has two arms, and you literally cannot forget the None case:

Rust match on an Option

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

if let and let-else

If you only care about the Some case, if let is shorter. If the code cannot continue without a value, let ... else returns early and keeps the rest of the function flat:

Rust if let and let-else with Option

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

unwrap and expect: the risky shortcuts

unwrap() returns the value inside Some and panics (crashes the thread with an error message) on None. expect("message") does the same but with your own message:

Rust unwrap on None (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

At run time this ends with exit code 101 and a message of this shape:

TEXT
thread 'main' (2) panicked at main.rs:3:31:
called `Option::unwrap()` on a `None` value

The panic is not a compiler error, because the compiler cannot know the vector is empty. You asked for a crash if it is, and you get one. So when are unwrap and expect appropriate?

  • In tiny examples and tests, to keep them short (this tutorial says so when it does).
  • When you can prove it is always Some: for instance right after checking is_empty(), though a cleaner design usually avoids needing the proof.
  • With expect("why this cannot fail") for programmer-error situations, where the message documents the assumption.

In ordinary program logic, prefer the safe tools below. A panic in a server or tool is almost always worse than a handled "not found".

Safe defaults: unwrap_or and friends

When a missing value has a sensible fallback, supply it:

Rust Providing defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

  • unwrap_or(value) takes a ready value. Use it for cheap constants.
  • unwrap_or_else(|| ...) takes a closure that runs only if needed. Use it when computing the default is costly or has side effects. (Closures are covered in Closures.)
  • unwrap_or_default() uses the type's Default value.

Transforming without unwrapping

Often you do not want to leave the Option at all. You want to say "if there is a value, do this to it, and keep the result optional". These methods do exactly that, and they chain nicely.

map, and_then and filter

Rust map, and_then, filter

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The difference between map and and_then trips up many beginners. map takes a function that returns a plain value U and gives Option<U>. If your function itself returns an Option<U>, using map would give you Option<Option<U>>; and_then removes the extra layer. ok_or converts to a Result, which carries an error message instead of nothing, and is a bridge to Result and Recoverable Errors.

Questions about an Option

A few small methods answer yes/no questions without unwrapping:

Rust is_some, is_some_and, is_none_or

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

is_some_and has been stable since Rust 1.70, is_none_or since 1.82. They replace the clumsy x.is_some() && x.unwrap() > 3, which works but invites a bug if someone edits one half.

Changing an Option in place: take and replace

Option shows up inside structs a lot (an optional next node, a maybe-open file). Two methods move the value out of a mutable Option, leaving something sensible behind:

Rust take and replace

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

take is the standard answer to the borrow-checker question "how do I move a value out of a field I only have &mut access to?" You will lean on it in linked structures later.

as_ref and as_deref: borrow instead of move

Most Option methods consume the Option. If you want to look inside without giving up ownership, call as_ref() (gives Option<&T>) or, for a String, as_deref() (gives Option<&str>):

Rust as_ref and as_deref

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

If you ever see the error "use of moved value" after calling map or unwrap_or on an Option<String> field, this is the cure. See References and Borrowing.

The ? operator on Option

A function that returns Option can use the ? operator on other Options. On Some(x) it gives you x; on None it returns None from the whole function immediately. A chain of steps that may each fail then reads as plain, linear code:

Rust ? with Option

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Each ? is a tiny early exit. initials("Plato") has a first word but no last word (words.last() after consuming the first returns None), so the function gives None. The ? operator is covered fully in The ? Operator.

Option and memory: no extra cost for references

You might wonder whether wrapping everything in Option is slow. For types that can never be all zeros, such as references, Box and String, Rust stores None in the unused bit pattern (the niche), so Option<&T> takes exactly as much memory as &T. That is how Rust gets null-style efficiency without null-style danger. Memory Layout and Sizes shows you how to measure it.

Design guidance

  • Use Option<T> when absence is a normal outcome with a single obvious meaning ("no match"). If the caller needs to know why something failed, return Result instead.
  • Do not use sentinel values such as -1, 0 or "" to mean "missing". That is the null-style bug in disguise.
  • Struct fields that are truly optional should be Option<T>. Do not make a field optional just to avoid initializing it.
  • Prefer Option<&T> (borrow) over Option<T> (own) in function parameters that only inspect the value.
  • Keep the code at the Option level using map, and_then and ?; unwrap only at the edge where you must produce a final plain value.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is Option<T> in Rust?

    Option is an ordinary enum: None for no value, Some(T) for a value. There is no null in safe Rust.
  2. 2. What happens when you call unwrap() on a None?

    unwrap panics on None at run time, with the message 'called Option::unwrap() on a None value'. The compiler cannot know in advance whether the value is present.
  3. 3. Which method should you use if your closure itself returns an Option and you do not want Option<Option<U>>?

    and_then (flat map) takes a function returning Option<U> and gives Option<U>. map would wrap the result a second time.
  4. 4. What does the ? operator do inside a function returning Option when the value is None?

    ? on None performs an early return of None from the enclosing function; on Some(x) it evaluates to x.
  5. 5. You have name: Option<String> and want its length without giving up ownership of the String. What is a good way?

    as_deref turns Option<String> into Option<&str> by borrowing, so name can be used again afterwards. unwrap and take would move or empty it, and Option has no len method.

Summary

  • Rust has no null. A value that may be absent has the type Option<T>: Some(value) or None.
  • The compiler forces you to handle None before using the value; an Option<i32> is not an i32.
  • Read an Option with match, if let or let ... else.
  • unwrap and expect panic on None; use them only in short demos, tests, or with expect to document a proven assumption.
  • Use unwrap_or, unwrap_or_else and unwrap_or_default for fallbacks.
  • Transform with map, and_then, filter, ok_or; ask questions with is_some_and and is_none_or.
  • take, replace and get_or_insert_with modify an Option in place; as_ref and as_deref borrow instead of move.
  • Inside functions that return Option, ? returns early on None.

Next: Ownership