Home > OS >  How to handle may panic if I know it is imposible to panic in rust
How to handle may panic if I know it is imposible to panic in rust

Time:01-22

I have a error on the first parsing: may panic if the index is out of bounds. But the if before parsing shoud handle this. How to handle the error correctly?

print!("Write 2 ints separated by space: ");
let mut nums_string: String = String::new();
stdout().flush().expect(ERR_MSG_STDOUT_FLUSH);
stdin()
    .read_line(&mut nums_string)
    .expect(ERR_MSG_STDIN_READ_LINE);
let nums_str_vec: Vec<&str> = nums_string.trim().split(' ').collect();
let num1: i32;
let num2: i32;
if nums_str_vec.len() == 2 {
    num1 = match nums_str_vec[0].parse() {
        Err(_) => panic!("Wrong input"),
        Ok(_) => nums_str_vec[0].parse().unwrap(),
    };
    num2 = match nums_str_vec[1].parse() {
        Err(_) => panic!("Wrong input"),
        Ok(_) => nums_str_vec[1].parse().unwrap(),
    };
} else {
    panic!("Wrong input");
}

Is possible to handle error without if and use only the match?

CodePudding user response:

The solution for handling "may panic" if you know it won't panic is to not repeat the code that may panic.

If you have already determined that it is a number by matching the Ok case, you do not need to parse it again.

The number is contained in the Ok value, which you currently ignore. Use it!

Ok(n) => n,

CodePudding user response:

Is possible to handle error without if and use only the match?

Complemeting mkrieger1's answer, a few additional transformations before the vec will give you a much simpler match thanks to slice patterns:

let nums: Vec<Result<i32, _>> = nums_string.trim().split_whitespace().map(str::parse).collect();
match nums[..] {
    [Ok(n1), Ok(n2)] => println!("{} {}", n1, n2),
    _ => println!("Wrong input"),
}
  • Related