Branch expressions

One of the things that makes programs truly useful is the ability for them to make decisions. We can do that in Rust by using an if expression. An if expression looks something like this:

if 3 > 4 {
println!("Uh-oh. Three is greater than four.");
}
else if 3 == 4 {
println!("There seems to be something wrong with math.");
}
else {
println!("Three is not greater than or equal to four.");
};
If you're familiar with other programming languages, you might be wondering where the parenthesis are around the condition expression. Rust's syntax doesn't call for parenthesis there. In fact, if we place the condition in parenthesis, the compiler will warn us that they're not necessary.

What we have here is an expression that shows off all the features of an if. It starts off with the keyword if, followed by a condition expression that produces either true or false, and then a block expression. If the condition expression produces true, the block expression is run, but if the condition expression produces false, the block expression is not run.

Using 3 > 4 as our condition expression is not very useful. We might as well just write false, or leave that block expression out entirely since it will never run. However, in real code, we would use a condition expression whose result we would not know at the time we were writing the code. Is it between the hours of 8 A.M. and 5 P.M., Did the user select this value from the menu, and Does the value match what is stored in the database are examples of more realistic conditions, though of course they would have to be expressed in Rust.

After that, we have an else if and another condition expression and block. That means that, if the first condition expression produced false, the computer should check whether the second one produces true, and if it does, run the associated block expression.

We can chain as many else if expressions as we want after an initial if, so there's no limit to the number of different options we can make available to the computer. However, only one of them will run after any given decision. The computer will start with the initial if and check the values of the conditional expressions one at a time until it finds one that produces true, then it will run the associated block expression, and then it will be done with the if expression and move on to the subsequent instructions.

After an if and any else if we might wish to include, we are allowed to put an else followed by a block expression. This is a branch without a condition, and what it means is if none of the condition expressions produced true, do this. In other words, it allows us to tell the computer what to do by default, if none of the special cases we provided apply.

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

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