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:
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
fn main() {
let some_number: Option<i32> = Some(5);
let no_number: Option<i32> = None;
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
fn main() {
let maybe_age: Option<u32> = Some(25);
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
fn main() {
let missing: Option<i32> = None;
let value = missing.unwrap_or(0);
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
fn find_even(numbers: &[i32]) -> Option<i32> {
for &n in numbers {
if n % 2 == 0 {
return Some(n);
}
}
None
}
fn main() {
let nums = [1, 3, 4, 7];
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: