Option Basic
Handle optional values with Option<T>.
Option Basic
Handle optional values with Option
Difficulty
Beginner
Code
fn find_index(haystack: &[i32], needle: i32) -> Option<usize> {
for (i, &item) in haystack.iter().enumerate() {
if item == needle {
return Some(i);
}
}
None
}
fn main() {
let nums = vec![10, 20, 30, 40, 50];
match find_index(&nums, 30) {
Some(i) => println!("found at index {}", i),
None => println!("not found"),
}
println!("not found: {:?}", find_index(&nums, 99));
}Explanation
Option represents Some(value) or None.
Key Concepts
- Read the code carefully and understand the data flow
- Try modifying the example to see how it changes behavior
- Run this code in the Rust Playground
Related Topics
Browse more examples in the error-handling category to build a complete understanding of this topic.