beginnerError Handling
Option Basic
Handle optional values with Option<T>.
Option Basic
Handle optional values with Option
Difficulty
Beginner
Code
rust
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
This example demonstrates how to use option basic in Rust. Read the code carefully to understand the flow. Pay attention to where values are created, borrowed, moved, or consumed.
Key Concepts
- Rust's strong type system catches errors at compile time
- Ownership and borrowing rules ensure memory safety
- Pattern matching makes code expressive and exhaustive
Related Topics
Browse more examples in the error-handling category to build a complete understanding of this topic.