HomeLinuxRust Fundamentals Collection #6: Utilizing If Else

Rust Fundamentals Collection #6: Utilizing If Else


Within the earlier article on this sequence, you checked out Features. On this article, let’s take a look at managing the management move of our Rust program utilizing conditional statements.

What are conditional statements?

When writing some code, one of the widespread duties is to carry out a verify for sure situations to be true or false. “If the temperature is increased than 35°C, activate the air conditioner.”

By utilizing key phrases like if and else (typically together), a programmer can change what this system does based mostly on situations just like the variety of arguments supplied, the choices handed from the command line, the names of recordsdata, error prevalence, and so on.

So it’s vital for a programmer to know management move in any language, not to mention in Rust.

Conditional operators

The next desk exhibits all of the ceaselessly used operators for a person situation:

Operator Instance Interpretation
> a > b a is better than b
< a < b a is much less than b
== a == b a is equal to b
!= a != b a is not equal to b
>= a >= b a is better than OR equal to b
<= a <= b a is lower than OR equal to b

And following is the desk for logical operators, they’re used between a number of situations:

Operator Instance Interpretation
|| (Logical OR) COND1 || COND2 A minimum of one of many situation COND1 or COND2 evaluates to true
&& (Logical AND) COND1 && COND2 All situations consider to true
! (Logical NOT) !COND Reverse boolean worth of what COND evaluates to

📋

Like in Arithmetic, you should utilize parentheses (spherical brackets) to specify the priority of an operation in comparison with others.

Utilizing if else

To deal with the essential move of Rust code, two key phrases are used: if and else. This helps you create two “execution paths” based mostly on the state of the supplied situation.

The syntax of a easy if block with another execution path is as follows:

if situation {
    <assertion(s)>;
} else {
    <assertion(s)>;
}

📋

When just one situation is supplied, enclosing it in spherical brackets will not be obligatory. The usage of spherical brackets is non-compulsory, in keeping with the syntax. It is best to nonetheless use them to specify priority and for higher readability.

Let’s take a look at an instance.

fn major() {
    let a = 36;
    let b = 25;

    if a > b {
        println!("a is larger than b");
    } else {
        println!("b is larger than a");
    }
}

Right here, I’ve declared two integer variables a and b with the values ’36’ and ’25’. On line 5, I verify if the worth saved in variable a is larger than the worth saved in variable b. If the situation evaluates to true, the code on line 6 will probably be executed. If the situation evaluates to false, as a consequence of the truth that we’ve got an else block (which is non-compulsory), the code on line 8 will get executed.

Let’s confirm this by wanting on the program output.

a is larger than b

Excellent!

Let’s modify the worth of variable a to be lower than worth of variable b and see what occurs. I’ll change a‘s worth to ’10’. Following is the output after this modification:

b is larger than a

However, what if I retailer the identical worth in variables a and b? To see this, I’ll set each variables’ worth to be ’40’. Following is the output after this explicit modification:

b is larger than a

Huh? Logically, this does not make any sense… 🙁

However this may be improved! Proceed studying.

Utilizing ‘else if’ conditional

Like every other programming language, you’ll be able to put an else if block to supply greater than two execution paths. The syntax is as follows:

if situation {
    <assertion(s)>;
} else if situation {
    <assertion(s)>;
} else {
    <assertion(s)>;
}

Now, with the usage of an else if block, I can enhance the logic of my program. Following is the modified program.

fn major() {
    let a = 40;
    let b = 40;

    if a == b {
        println!("a and b are equal");
    } else if a > b {
        println!("a is larger than b");
    } else {
        println!("b is larger than a");
    }
}

Now, the logic of my program is appropriate. It has dealt with all edge circumstances (that I can consider). The situation the place a is the same as b is dealt with on line 5. The situation the place a could be better than b is dealt with on line 7. And, the situation the place a is lower than b is intrinsically dealt with by the else block on line 9.

Now, after I run this code, I get the next output:

a and b are equal

Now that is excellent!

Instance: Discover the best

I do know that the usage of if and else is simple, however allow us to have a look at yet another program. This time, let’s evaluate three numbers. I will even make use of a logical operator on this occasion!

fn major() {
    let a = 73;
    let b = 56;
    let c = 15;

    if (a != b) && (a != c) && (b != c) {
        if (a > b) && (a > c) {
            println!("a is the best");
        } else if (b > a) && (b > c) {
            println!("b is the best");
        } else {
            println!("c is the best");
        }
    }
}

This may look difficult at first sight, however worry not; I shall clarify this!

Initially, I declare three variables a, b and c with random values that I might consider at the moment. Then, on line 6, I verify for the situation the place no variable’s worth is identical as every other variable. First, I verify the values of a and b, then a and c after which b and c. This manner I can make certain that there aren’t any duplicate values saved in both variable.

Then, on line 7, I verify if the worth saved in variable a is the best. If that situation evaluates to true, code on line 8 will get executed. In any other case the execution path on line 9 is checked.

On line 9, I verify if the worth saved in variable b is the best. If this situation evaluates to true, code on line 10 will get executed. If this situation can be false, then it means just one factor. Neither variable a, nor variable b is the best amongst all 3.

So naturally, within the else block, I print that the variable c holds the best worth.

Let’s confirm this with this system output:

a is the best

And that is as anticipated. Attempt to modify the values assigned to every variable and check it out your self! 🙂

Conclusion

You discovered to make use of if and else statements. Earlier than you go on making your individual AI with misplaced of if else-if statements (haha), let’ study loops in Rust within the subsequent chapter of the sequence.

Keep tuned.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments