How to handle error so program does not crash?

In the following code, I rightfully get a panic that crashes the program.
How would I handle the error in this case so the app can show a dialog and log the error without the app crashing?

pub fn main() {
    let mut white_pos_tuple_vec: Vec<(f64, f64)> = Vec::new();
    white_pos_tuple_vec.push((4.0, 5.0));
    white_pos_tuple_vec.push((5.0, 6.0));
    white_pos_tuple_vec.push((7.0, 8.0));
    white_pos_tuple_vec.push((9.0, 10.0));

    let index = white_pos_tuple_vec
        .iter()
        .position(|&x| x.0 == 7.0 && x.1 == 9.0)
        .unwrap();
    println!("{}", index);

    println!("Index value of tuple = {:?}", white_pos_tuple_vec[index]);
}

thread 'main' panicked at 'called `Option::unwrap()` on a `None` value', src/main.rs:8:17
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Instead of unwrap, you can use match:

    let opt: Option<usize> = white_pos_tuple_vec
        .iter()
        .position(|&x| x.0 == 7.0 && x.1 == 9.0);
    
    match opt {
        Some(index) => {
            println!("{}", index);
            println!("Index value of tuple = {:?}", white_pos_tuple_vec[index]);
        }
        None => {
            println!("Sorry, couldn't find it.")
        }
    }

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.