Categories
Programming

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

Categories
Programming

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!");
}