rust / beginner
Snippet
Working with Option<T> for Optional Values
Option<T> is Rust's way of handling values that may or may not exist, eliminating null pointer exceptions. Instead of returning null, you return Some(value) or None. The if let syntax unwraps the value only if it exists, making code readable and safe. The unwrap_or method provides a default value when None is encountered.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
fn find_user(id: u32) -> Option<String> {if id == 1 {Some(String::from("Alice"))} else {None}}fn main() {let user = find_user(1);// Using if let to extract the valueif let Some(name) = user {println!("Found user: {}", name);} else {println!("User not found");}// Using unwrap_or for default valuelet another_user = find_user(999).unwrap_or(String::from("Guest"));println!("Another user: {}", another_user);}
Breakdown
1
fn find_user(id: u32) -> Option<String> {
Function returns Option<String> instead of a plain String
2
Some(String::from("Alice"))
Returns Some with a value when user is found
3
None
Returns None when user does not exist
4
if let Some(name) = user {
Extracts value from Option only if it's Some