Exit instead of panic


#1

This is a beginner question.

I want to parse a number and in case of an error I want to exit the program gracefully The following code works but I’m not sure if I could do it in a better way.

#[allow(unreachable_code)]
fn to_int(s: &str) -> u32 {
match s.parse::() {
Ok(i) => i,
Err(_) => { eprintln!(“Not a number: {}”, s); ::std::process::exit(1); 0 }
}
}

Thanks, Manfred

BTW: How could I format source code as such?


#2

You can use unwrap_or_else to make it a bit nicer:

fn to_int(s: &str) -> u32 {
    s.parse::().unwrap_or_else(|| {
        eprintln!(“Not a number: {}”, s);
        ::std::process::exit(1);
    }
}

BTW: How could I format source code as such?

use triple backticks; it’s markdown.


#3

Hi.

You can do:

fn to_int(s: &str) -> u32 {
  s.parse().expect("not a number")
}

Also: while sharing code here specify ```rust and format it properly to make it easier for people to read.

Edit: this might not “exit gracefully” to your liking :stuck_out_tongue:


#4

Thanks.

Your suggestion

fn to_int(s: &str) -> u32 {
    s.parse::<u32>().unwrap_or_else(|e| {
        eprintln!("Not a number: {}", e);
        ::std::process::exit(1);
    })
}

is indeed nicer than what I had.