OneBite.Dev - Coding blog in a bite size

Use If Conditional Statement In Rust

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

If conditional statements in Rust facilitate logical programming where you can execute different blocks of code based on certain conditions. In this article, we will explore how to use ‘if’ conditional statements in Rust and examine practical examples to better understand how they function.

Code snippet: Using IF Conditional Statements in Rust

fn main() {
    let number = 5;

    if number < 0 {
        println!("The number is negative");
    } else if number > 0 {
        println!("The number is positive");
    } else {
        println!("The number is zero");
    }
}

Code Explanation: Using IF Conditional Statements in Rust

The code block above is a basic demonstration of how an ‘if’ conditional statement operates in Rust. Let’s break it down:

We start by declaring a function main() where our main program resides. In the function, we introduce a number variable assigned an integer value of 5.

Then, we implement our ‘if’ conditional statement. The syntax used is similar to most other programming languages where the condition follows the if keyword. This condition checks if number is less than 0, and if so, prints that the number is negative. Hence, in the first if condition, the test number < 0 fails because 5 is not less than 0.

In a scenario where the first test fails (as in our case), the program then checks the conditions in the else if statement. Here, the test is number > 0. The result of this test is true, so the output will be “The number is positive”.

In the event that both the if and else if conditions fail, the program defaults to the else block. Here, it will print “The number is zero”. However, as our number was 5, this block of code is not executed.

Remember that Rust will run the first block where the condition evaluates to true, and as soon as it finds a positive condition, it won’t check the subsequent ones.

And there we have it! That’s a simple demonstration of how to use the ‘if’ conditional statement in Rust. These statements are crucial for implementing logic in your code, and the beauty of Rust is that its syntax makes it intuitive and easy to implement this logic.

rust