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

Conditionals and decision making

Conditionals are also similar to how they're found in other languages. They follow the C-like if {} else {} structure:

// if_else.rs

fn main() {
let rust_is_awesome = true;
if rust_is_awesome {
println!("Indeed");
} else {
println!("Well, you should try Rust !");
}
}

In Rust, the if construct is not a statement, but an expression. In general programming parlance, statements do not return any value, but an expression does. This distinction means that if else conditionals in Rust always return a value. The value may be an empty () unit type, or it may be an actual value. Whatever remains in the last line inside the braces becomes the return value of the if else expression. It is important to note that both if and else branches should have the same return type. Also, we don't need parentheses around the if condition expression, as you can see in the preceding code. We can even assign the value of if else blocks to a variable:

// if_assign.rs

fn main() {
let result = if 1 == 2 {
"Wait, what ?"
} else {
"Rust makes sense"
};

println!("You know what ? {}.", result);
}

When assigning values that have been returned from an if else expression, we need to end them with a semicolon. For example, if { ... is an expression, while let is a statement that expects us to have a semicolon at the end. In the case of assignment, if we were to remove the else {} block from the preceding code, the compiler would throw an error, like so:

Without the else block, if the if condition evaluates to false, then the result will be (), and there would be two possible values for the result variable, that is, () and &str. Rust does not allow multiple types to be stored in one variable. So, in this case, we need both the if {} and else {} blocks returning the same types. Also, adding a semicolon in the conditional branches changes the meaning of the code. By adding a semicolon after the strings in the if block in the following code, the compiler would interpret it as you wanting to throw the value away:

// if_else_no_value.rs

fn main() {
let result = if 1 == 2 {
"Nothing makes sense";
} else {
"Sanity reigns";
};

println!("Result of computation: {:?}", result);
}

In this case, the result will be an empty (), which is why we had to change the println! expression slightly (the {:?}); this type cannot be printed out in the regular way. Now, for the more complex multi-valued decision making; Rust has another powerful construct called match expressions, which we'll look at next.

主站蜘蛛池模板: 锡林浩特市| 陆河县| 枣阳市| 桐柏县| 西丰县| 铜山县| 库车县| 大英县| 寿宁县| 甘谷县| 辽源市| 北流市| 民和| 大兴区| 尉氏县| 精河县| 东港市| 晋中市| 宿松县| 肇庆市| 体育| 永宁县| 河间市| 青铜峡市| 乐安县| 邵武市| 丰城市| 鄂伦春自治旗| 葫芦岛市| 济南市| 北票市| 安康市| 虞城县| 沙雅县| 长岛县| 东乌珠穆沁旗| 阳高县| 云阳县| 固镇县| 溧水县| 望谟县|