rust / intermediate
Snippet
Option<T> for Null Safety
Rust has no null values. Instead, Option<T> represents optional values: Some(T) contains a value, None represents absence. This makes null pointer exceptions impossible at compile time. The if let syntax provides convenient pattern matching, while unwrap_or offers a safe default fallback.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fn find_user(id: u32) -> Option<&'static str> {match id {1 => Some("Alice"),2 => Some("Bob"),_ => None,}}fn main() {let user = find_user(1);if let Some(name) = user {println!("Found: {}", name);} else {println!("User not found");}// Using unwrap_or for default valueslet missing = find_user(999).unwrap_or("Guest");println!("Missing user: {}", missing);}
Breakdown
1
fn find_user(id: u32) -> Option<&'static str>
Function returns Option — either Some(name) or None
2
Some("Alice")
Wraps value in Some variant of Option
3
_ => None
Wildcard pattern returns None for unmatched cases
4
if let Some(name) = user { ... }
Conditional binding extracts value only if Some, avoiding explicit match
5
.unwrap_or("Guest")
Returns contained value or provided default if None