RRust By Example

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

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.

Common Compiler Errors in This Topic

Use these error pages as a debugging companion while practicing this example category.

More Error Handling Examples