Categories
Programming

Learning something new : RUST lang PART 32 min read

Error Handling

In the previous one where we built a guess the number game in rust, we did not handle any errors. The obvious error was that if something other than a number was inputted the program would crash.

Now that I have learnt how to correct this, lets change the code a little bit.

This was the code without error handling.

use std::io;

fn main() {

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;
    let mut line = String::new();

    //get user input
    stdin.read_line(&mut line).unwrap();

    //Parse input string to integer
    //Not error handled
    guess = line.trim().parse().unwrap();

}

The parse() method returns a result object. The result object would have Ok() and Err() values. So if it is OK we can run a function with the parsed value passed to it. If it is an error we can handle it gracefully and say “Listen idiot, you have to enter a number. A NUMBAAA”.

For this we use the match function or statement or whatever it is called. It seem to act like the switch statement.

So here is the update code for the number guessing game.

use std::io;

fn main() {

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;
    let mut line = String::new();

    //get user input
    stdin.read_line(&mut line).unwrap();

    //Parse input string to integer
    //Error handled 
    guess = match line.trim().parse() {
        Ok(num) => num,
        Err(_) =>{
            println!("Please enter a number");
            return;
        }
    };
}

With the loop and game –

use std::io;
extern crate rand;
use rand::Rng;

fn main() {
    //Generate a random number
    let num = rand::thread_rng().gen_range(0, 10);

    println!("Guess a number");

    let stdin = io::stdin();
    let mut guess: i32;

    while ( true ){
        let mut line = String::new();

        //get user input
        stdin.read_line(&mut line).unwrap();

        //Parse input string to integer
        //Error is handled
        guess = match line.trim().parse() {
            Ok(num) => num,
            Err(_) =>{
                println!("Please enter a number");
                continue;
            }
        };

        //If the guess is correct exit the loop
        if( guess == num ){
            println!("Correct the number was {}", guess);
            break;
        }
        else{
            println!("Wrong. Not {}", guess);
        }
    }
}

There you go rust book, I beat you at your own game.

//Also instead of using

while( true ){
    //code
}

//You could just do this

loop{
    //code
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *