capypad
0 day streak
rust / beginner
Snippet

Handling Optional Values with Option

Option<T> represents a value that might exist or not, avoiding null references. Some contains a value, None represents absence. The if let syntax provides concise pattern matching, while unwrap_or provides a default value.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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);
}
let unknown = find_user(999);
println!("User: {:?}", unknown.unwrap_or("Guest"));
}
Breakdown
1
fn find_user(id: u32) -> Option<&'static str>
Returns Some(name) or None depending on id
2
if let Some(name) = user
Executes block only if user is Some, binds value to name
3
unwrap_or("Guest")
Returns the value inside Some, or the default if None