capypad
0 day streak
rust / beginner
Snippet

Working with Option<T>

Option<T> represents a value that may or may not exist. Some(T) contains a value, None represents absence. Unlike null in other languages, Option is type-checked at compile time. The if let syntax provides pattern matching for Option, and 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_element(arr: &[i32], target: i32) -> Option<usize> {
arr.iter().position(|&x| x == target)
}
 
fn main() {
let data = vec![10, 20, 30, 40];
let result = find_element(&data, 30);
if let Some(index) = result {
println!("Found at index: {}", index);
}
let missing = find_element(&data, 100);
println!("Missing: {:?}", missing);
let idx = find_element(&data, 20).unwrap_or(usize::MAX);
println!("Index or default: {}", idx);
}
Breakdown
1
.position(|&x| x == target)
Returns Option<usize>: Some(index) if found, None otherwise
2
if let Some(index) = result
Destructures Option using pattern matching
3
.unwrap_or(usize::MAX)
Returns value inside Some, or default value if None