官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 万年县| 抚顺市| 上林县| 瑞丽市| 江达县| 綦江县| 石台县| 富顺县| 缙云县| 武隆县| 正宁县| 遂昌县| 隆回县| 绥中县| 武定县| 隆林| 麦盖提县| 高要市| 新竹县| 宜州市| 成都市| 蓬莱市| 偃师市| 平顶山市| 台北县| 五家渠市| 韶山市| 巩义市| 漳州市| 鸡泽县| 于田县| 金昌市| 海安县| 兴和县| 河津市| 长治市| 青河县| 梅州市| 新乡县| 常山县| 施甸县|