Rust Systems & Tokio (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
What are the `Option<T>` and `Result<T, E>` enums?
junior LevelCode ExampleTypeScript
In Simple Words:
Rust does not have null or exceptions!
Option<T>: Represents either a value (Some(T)) or absence of a value (None):- Eliminates the billion-dollar Null Pointer Exception at compile time.
Result<T, E>: Represents either success with a value (Ok(T)) or failure with an error (Err(E)).- Must be handled exhaustively using
match,if let, or the?operator.
rust
fn divide(numerator: f64, denominator: f64) -> Result<f64, String> {
if denominator == 0.0 {
Err(String::from("Cannot divide by zero"))
} else {
Ok(numerator / denominator)
}
}