Rust basics part 3 - Writing an working game

·

2 min read

So last part we saw how to get an input from the user and give an output . Today we are going to write an actual game.

Guessing game

So this is a simple guessing game written in rust.

use std::io;

fn main() {
    println!("Guess the age of timmy!(He's a teenager)");    
    println!("Please input your guess.");

    let mut guess = String::new();

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

    if  guess == 15 {
        println!("Good , you guessed timmy's age right");
    }
    else {
        println!("Sorry, your guess is wrong");
    }
}

Here we use std::io library for the input output functions and basic three println! lines and a mutable variable ( let mut guess) and the function itself ( io::stdin() ).

But there are other statements like the if and else if you might ask they are boolean keywords.

Boolean

So this is a another data type like integers, floats . It is basically the comparing operators like < , > , == etc. The " == " means if it was equal to that number , So the if statement states that if the variable " guess " was or is equal to 15 then it'll print or execute anything in the parameter "{}" , printing Good , you guessed timmy's age right .

Else statement is used when if state is not satisfied . Here if the "guess" isn't equal to 15 if it is something other than 15 it'll execute the code in it's parameters " {} " , printing Sorry, your guess is wrong .

Exercise :

( 1 ) -- Write a simple code for an yes or no question with the if and else statement

Note :

Please kindly check the previous Rust Basics article series for updates now an then.