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
}

 

Learning something new : RUST lang PART 23 min read

The second part is creating a guessing game in rust.

From the book this is what is going to happen.

We’ll implement a classic beginner programming problem: a guessing game. Here’s how it works: the program will generate a random integer between 1 and 100. It will then prompt the player to enter a guess. After entering a guess, it will indicate whether the guess is too low or too high. If the guess is correct, the game will print congratulations and exit.

I tried to create a simple guessing game myself before looking at this. The program would ask the user for a number between 0 and 10.  If the input is equal to a random number generated by the program, the user wins.

But I needed to know

  • How to create a random number in rust within a given range/
  • How to get input from user.
  • How to convert the input string to an integer.

After a lot of google search and trial and error, I finally succeeded.

Random number generation

Using this package or what is known as crate in rust.

https://doc.rust-lang.org/rand/rand/index.html

Added this to the Cargo.toml file.

[dependencies]
rand = "0.3"

And the code –

extern crate rand;
use rand::Rng;

fn main() {
    let num = rand::thread_rng().gen_range(0, 10);
}

Getting input from user

use std::io;

fn main() {
    let stdin = io::stdin();
    let mut line = String::new();
    stdin.read_line(&mut line).unwrap();
}

Its done through the standard io (std::io) library.

Now what is that after the let keyword?

From what I understand, if you do not add mut after the let keyword, you are declaring a constant, but if you add mut its a variable.

If you are passing something by reference  like in

stdin.read_line(&mut line).unwrap();

If the function changes the value of the passed paramenter you should add &mut.

Examples –

fn main() {
    let a = 1;
    a = 5; //(Error: re-assignment of immutable variable)
}
fn main() {
    let mut a = 1;
    a = 5; //(No error)
}

More – https://doc.rust-lang.org/book/first-edition/mutability.html

.unwrap()

If there is and error, it would throw the error and exit the program.

Converting a string to an integer

use std::io;

fn main() {
    let stdin = io::stdin();
    let mut line = String::new();
    let mut num: i32;
    stdin.read_line(&mut line).unwrap();
    num = line.trim().parse().unwrap();
    println!("The number is {}", num);
}

Note – Not error handled, because I have no idea how to do it yet.

So, from what I found

  • you can declare and integer variable at top and set it value to string.parse() or
  • Use
    let num  = line.trim().parse::<i32>();

    and check for errors.

At last it is done

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
        //Not error handled
        guess = line.trim().parse().unwrap();
        
        //If the guess is correct exit the loop
        if( guess == num ){
            println!("Correct the number was {}", guess);
            break;
        }
        else{
            println!("Wrong. Not {}", guess);
        }
    }

}

The guessing game – https://doc.rust-lang.org/book/second-edition/ch02-00-guessing-game-tutorial.html

Learning something new : RUST lang PART 119 sec read

Note – This is not a tutorial. This is me trying to learn a new language.

This is the book that I am learning rust from –  The Rust Programming Language.

I am using windows, so I had to set the path to rest bin after installing.

Hello world in rust.

fn main() {
    println!("Hello, world!");
}