capypad
0 day streak
rust / beginner
Snippet

Option<T>: Handling Missing Values Safely

Option<T> is Rust's type for representing a value that might exist or not. It has two variants: Some(T) when a value is present, and None when absent. This forces you to handle both cases, eliminating null pointer errors at compile time.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
fn find_element(arr: &[i32], target: i32) -> Option<usize> {
for (index, &value) in arr.iter().enumerate() {
if value == target {
return Some(index);
}
}
None
}
 
fn main() {
let numbers = [10, 20, 30, 40, 50];
// Using match to handle Option
let result = find_element(&numbers, 30);
match result {
Some(index) => println!("Found at index: {}", index),
None => println!("Element not found"),
}
// Using if let for concise handling
if let Some(index) = find_element(&numbers, 25) {
println!("Found at index: {}", index);
} else {
println!("Element not found with if let");
}
// Using unwrap_or for default values
let index = find_element(&numbers, 100).unwrap_or(999);
println!("Index or default: {}", index);
}
Breakdown
1
fn find_element(arr: &[i32], target: i32) -> Option<usize>
Function returns Option<usize> which is either Some(index) or None
2
return Some(index);
Returns Some variant with the index when element is found
3
None
Returns None variant when loop completes without finding the element
4
if let Some(index) = find_element(&numbers, 25)
Pattern matching that extracts value from Some, or runs else block for None
5
unwrap_or(999)
Returns the contained value or a default if None