Error Handling with Option | Rust Fundamentals lesson | BraveProgrammer
Lesson 18 of 50
·rust
Error Handling with Option
15 minutes
Course progress36%
Error Handling with Option
Option<T> represents a value that may or may not exist. It replaces null pointers from other languages, making the absence of a value explicit in the type system.
The Option Type
enumOption<T> {
Some(T),
None,
}
It's so common you don't need to prefix it with std::option::
fnmain() {
letx: Option<i32> = Some(5);
// Traditional approachlety = match x {
Some(val) => Some(val * 2),
None => returnNone,
};
// But Option<T> expects the function to also return Option
}
fndouble_optional(x: Option<i32>) ->Option<i32> {
Some(x? * 2) // Returns None if x is None
}
Why Option Over Null?
Explicit: Absence is part of the type
Safe: Can't access None as a value
Composable: Chain operations with map, and_then
Forces handling: Compiler requires you to handle None case
Make it stickPractice what you've learned1 quiz · 1 practical test · Optional activities from Rust FundamentalsBrowse activities