ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)
Set your Publisher ID in src/config/ads.ts to display live ads.
Rust Tutorial• 7 min read
Structs, Enums & The Option<T> Type
Why Rust has no NULL: The Option<T> enum (Some vs None) and match expressions
Rust replaces Null with the Option<T> enum. A value is either Some(value) or None. The compiler forces you to handle the None case explicitly before extracting data.
Eliminating Null Pointer Exceptions with Option<T>
Definition: enum Option<T> { Some(T), None }.
Pattern Matching with match: Exhaustively matches both Some and None states.
The compiler guarantees you cannot accidentally access a None value as if it were valid data.
Pattern Matching with Option<T>
fn find_user_email(user_id: u32) -> Option<String> {
if user_id == 101 {
Some(String::from("admin@codexia.org"))
} else {
None
}
}
fn main() {
let email_result = find_user_email(101);
// Exhaustive pattern matching enforces handling both states
match email_result {
Some(email) => println!("Found user email: {}", email),
None => println!("User not found!"),
}
}ADVERTISEMENT
Google AdSense Slot (inContentBanner)
Set your Publisher ID in src/config/ads.ts to display live ads.
Test Yourself With Exercise
How does Rust represent the potential absence of a value without using null pointers?