How it works...

In this recipe, we implemented an if...else statement to perform conditional statements in Rust. The conditions are performed in the age variable. In this recipe, we assigned an immutable variable taking the value 10; after this, we compared it with various rules and performed an action based on the qualifying rule.

These rules are the conditions that the developer generates in the form of a mathematical operation that yields a result of true or false. Based on the output of the operation, we select a particular set of actions inside the scope of the decision statement.

The if...else statements are a great tool for developers to route the program logic. They are ideal for comparing thresholds at the end state of the application for making a logical decision.

In the preceding case, we checked three cases in the following flow:

  • The if statement checks whether the age variable is less than 18. If the operation returns true, then we go ahead and print Go to School.
  • The next condition is checked in the else...if statement when the first condition returns false; here we check whether the age is between 18 and 28, and if this condition returns true, we print Go to college.
  • Lastly, we have the else statement, which has no condition and is executed only when all the preceding conditions fail.

It's often a very important skill to write in a very optimized manner. We should learn the ability to develop the skill of writing less and optimized code.

The preceding set of statements contains a lot of lines of code, but we can write it in an optimized way, where we would have the if...else statement along with the condition in a single line. The general syntax for this case is as follows:

    let variable = if (condition 1 ) {true} else {false};

We have a variable to which we assign the if the condition 1 operation produces true; alternatively, we assign the value from the else statement.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.53