Rust Reference ยท Option and Result
Rust Option<T> type
Reference for Rust's Option<T> enum: Some and None, why Rust has no null, creating and inspecting options, size optimization, and the most useful methods.
Option<T> is the standard enum for a value that may be absent. It has two variants: Some(T) holds a value and None holds nothing. Rust has no null references; wherever a value could be missing, the type says so, and the compiler forces you to handle both cases before you can use the inner value.
Option and its variants are in the prelude, so you write Some(3) and None without imports. The type is defined as enum Option<T> { None, Some(T) }, and a large API on top of it replaces most manual match code.
let name: Option<&str> = Some("Ada"); let nothing: Option<i32> = None;
Try it
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.
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.
Syntax
pub enum Option<T> { None, Some(T), }
| Part | Description |
|---|---|
Some(value) |
A present value of type T. |
None |
No value. The type is inferred or written with an annotation: None::<i32>. |
Option<T> |
Implements Clone, Copy (if T: Copy), PartialEq, Eq, PartialOrd, Ord (None < Some(_)), Hash, Default (None), Debug, IntoIterator and From<T>. |
Edge cases: Option<T> is not T; you cannot add Some(1) + 1. Option<Option<T>> is a distinct type and is useful for "present but empty" cases. Comparing Some(1) < None is false because None is smaller.
Usage notes
- Handling. Use
match,if let,let ... else, or combinators such asmap,unwrap_orandok_or. - Do not unwrap casually.
unwrap()andexpect()panic onNone. Use them for impossible cases or tests, and giveexpecta message that states the broken assumption. - The
?operator works in functions returningOption: it returnsNoneearly. See?operator. - Niche optimization. For references,
Box,Rc,NonZerointegers and many enums,Option<T>is the same size asT, withNonestored in an invalid bit pattern. Plain integers get an extra tag (Option<u32>is 8 bytes). - Iteration. An
Optionis an iterator of zero or one item, sofor x in opt,.iter()and.chain(opt)work;flatten()over a sequence of options drops theNones. - Ownership. Methods like
unwrapconsume the option; useas_ref()oras_mut()to borrow, andtake()to move the value out in place. - Result vs Option. Use
Optionwhen absence is normal and carries no reason; useResultwhen you must explain why something failed.