The Option Type
Option is Rust's safe way of saying "there might be a value here, or there might be nothing" without ever using null.In this page:
enum Option<T> {
Some(T),
None,
}
let value: Option<Type> = Some(v);
What Is Option
Option<T> is an enum with two variants: Some(value) when a value is present, and None when it is absent. It replaces the concept of null found in many other languages.
Example: What Is Option
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `some_number` (a `Option<i32>`), set to `Some(5)`
let some_number: Option<i32> = Some(5);
// Declare an immutable variable `no_number` (a `Option<i32>`), set to `None`
let no_number: Option<i32> = None;
// Print "{:?} and {:?}" to the console, substituting in `some_number, no_number` (with a trailing newline)
println!("{:?} and {:?}", some_number, no_number);
}
Login to try C/C++/Java/PHP code in the editor
Matching on Option
match lets you safely handle both possibilities of an Option, extracting the inner value in the Some case and handling absence explicitly in the None case.
Example: Matching on Option
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `maybe_age` (a `Option<u32>`), set to `Some(25)`
let maybe_age: Option<u32> = Some(25);
// Match on `maybe_age` and branch by pattern
match maybe_age {
Some(age) => println!("Age is {}", age),
None => println!("No age provided"),
}
}
Login to try C/C++/Java/PHP code in the editor
Using unwrap_or for a Default
.unwrap_or(default) returns the inner value if present, or a fallback default value if the Option is None, avoiding the need for a full match for simple cases.
Example: Using unwrap_or for a Default
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `missing` (a `Option<i32>`), set to `None`
let missing: Option<i32> = None;
// Declare an immutable variable `value`, set to `missing.unwrap_or(0)`
let value = missing.unwrap_or(0);
// Print "Value: {}" to the console, substituting in `value` (with a trailing newline)
println!("Value: {}", value);
}
Login to try C/C++/Java/PHP code in the editor
Functions Returning Option
Functions that might not have a meaningful result to return use Option<T> as their return type, forcing every caller to explicitly handle the possibility of None.
Example: Functions Returning Option
// Define the function `find_even` taking `numbers` and returning a `Option<i32>`
fn find_even(numbers: &[i32]) -> Option<i32> {
// Loop over `numbers`, binding each item to `&n`
for &n in numbers {
// Check whether `n % 2 == 0`
if n % 2 == 0 {
// Return `Some(n)` from this function
return Some(n);
}
}
None
}
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `nums`, set to `[1, 3, 4, 7]`
let nums = [1, 3, 4, 7];
// Match on `find_even(&nums)` and branch by pattern
match find_even(&nums) {
Some(n) => println!("Found even number: {}", n),
None => println!("No even number found"),
}
}
Login to try C/C++/Java/PHP code in the editor
- Trying to use an
Option<T>value directly as if it were aT, without unwrapping or matching it first. - Calling
.unwrap()on anOptionthat might beNone, which panics the program at runtime. - Assuming Rust has a
nullvalue like other languages -- Rust deliberately has no null;Option::Nonereplaces that concept safely.
Option<T>represents a value that is eitherSome(value)orNone.- Rust has no null pointers;
Optionforces you to explicitly handle the 'no value' case. match,if let, and combinator methods like.unwrap_or()are common ways to safely handle anOption.- Using
Optionmoves the possibility of 'no value' into the type system, catching missing-value bugs at compile time.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: