OneBite.Dev - Coding blog in a bite size

If Else Conditional Statement In Rust

Code snippet for how to If Else Conditional Statement In Rust with sample and detail explanation

Rust is a fast and memory-safe language used to create reliable and efficient software. One of its most essential features is the use of conditional statements, especially the ‘if else’ statement, which gives developers the power to control the flow of their code.

Code snippet for If Else Conditional Statement in Rust

Here’s a basic example of an ‘if else’ conditional statement in Rust:

fn main() {
    let number = 7;

    if number < 5 {
        println!("The number is less than 5");
    } else {
        println!("The number is not less than 5");
    }
}

Code Explanation for If Else Conditional Statement in Rust

In the above code snippet, an ‘if else’ conditional statement is used to compare a number, declared as 7, with the number 5. The code inside the ‘if’ clause is executed when the condition evaluates to ‘true’, and if ‘false’, the code inside the ‘else’ clause is executed.

The fn main() function is the primary or main function that gets executed when the program runs.

Within the main function, let number = 7; declares a variable named ‘number’ and assigns the integer value 7 to it.

Then comes the ‘if else’ conditional statement. The condition specified within the parentheses of the ‘if’ statement is number < 5, which checks if the variable ‘number’ is less than 5.

If this condition is satisfied (i.e., if ‘number’ is indeed less than 5), the code following the ‘if’ statement, println!("The number is less than 5");, is executed, and the string “The number is less than 5” is printed to the console.

If the condition is not satisfied (i.e., ‘number’ is not less than 5), the code following the ‘else’ statement, println!("The number is not less than 5"); is executed, and the string “The number is not less than 5” is printed to the console.

In the aforementioned code snippet, since ‘number’ is declared as 7 and hence is not less than 5, “The number is not less than 5” is printed when the program is run.

rust