rust / intermediate
Snippet
Pattern Matching with Option and Result
Rust's Option and Result types are powerful error handling constructs. The ? operator propagates errors early, while match expressions with guards let you handle different cases elegantly. This pattern replaces traditional null checks and exception handling.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fn find_user(id: u32) -> Option<String> {if id == 1 {Some(String::from("Alice"))} else {None}}fn greet_user(id: u32) -> Result<String, String> {let name = find_user(id).ok_or("User not found".to_string())?;match name.len() {n if n > 10 => Ok(format!("Hello, {}!", name)),n if n > 5 => Ok(format!("Hi, {}", name)),_ => Ok(format!("Hey {}", name)),}}fn main() {match greet_user(1) {Ok(greeting) => println!("{}", greeting),Err(e) => println!("Error: {}", e),}}
Breakdown
1
fn find_user(id: u32) -> Option<String>
Function returns Option<String>, Some contains name, None means not found
2
.ok_or("User not found".to_string())?
Converts Option to Result, ? returns Err early if None
3
match name.len() { ... }
Pattern matching with guards (n if condition) checks name length
4
_ => Ok(format!("Hey {}", name))
Wildcard pattern handles remaining case, returns Ok