rust / beginner
Snippet
Working with Option<T>
Option<T> is Rust's safe alternative to null. It has two variants: Some(value) when a value exists, or None when it doesn't. This forces you to handle the absence case explicitly, preventing null pointer errors.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
fn find_element(arr: &[i32], target: i32) -> Option<usize> {for (i, &item) in arr.iter().enumerate() {if item == target {return Some(i);}}None}fn main() {let nums = [1, 3, 5, 7];match find_element(&nums, 5) {Some(idx) => println!("Found at index {}", idx),None => println!("Not found"),}if let Some(idx) = find_element(&nums, 2) {println!("Found at {}", idx);}}
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(i);
Returns Some(index) wrapped in the Option enum
3
None => println!("Not found")
Handle the case where element was not found
4
if let Some(idx) = find_element(&nums, 2)
Compact pattern matching when we only care about the Some case