I like taking a look at other languages. I’ve recently started looking at Rust. What I like most about Rust is how it handles errors. From the starting guide:

println!("Please input your guess.");

let mut guess = String::new();

io::stdin().read_line(&mut guess)
    .ok()
    .expect("failed to read line");

let guess: u32 = guess.trim().parse()
    .ok()
    .expect("Please type a number!");

println!("You guessed: {}", guess);

The previous code asks the user for number. Rust reads it in through the io::stdin library. We expect the the guess to be a number. If it is ok, great, we can move on and execute others. If it doesn’t it errors out and the program stops. I like how each line automatically has to handle errors. It makes the designer think up front on how to handle errors. To often code is written and errors are handle as an afterthought.

So how do we move from ‘crash on error’ to actually handle the error?

let guess: u32 = match guess.trim().parse() {
    Ok(num) => num,
    Err(_) => continue,
};

We have to switch to a match statement. If it is ok we have a number, else we just continue and again ask for a number. I find it off that we have to switch from a chaining syntax to wrapped match statement to actually handle the error. Personally the complete change from ‘fail on error’ to handle the error is a huge jump. I wish the following could be written.

let guess: u32 = guess.trim().parse()
    .ok()
    .expect("Please type a number!")
    .error(Handle the error)

I am by no means a language designer and understand that this could be very difficult. But if Rust is going to make you deal with errors out front the syntax shouldn’t change very much between failing and catching the error.

Comments