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

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.

主站蜘蛛池模板: 福建省| 芜湖市| 巴里| 青浦区| 平泉县| 格尔木市| 沐川县| 浦东新区| 襄城县| 房山区| 合肥市| 平武县| 大名县| 桦川县| 恩施市| 崇信县| 浙江省| 那坡县| 金昌市| 荃湾区| 东阳市| 济宁市| 宜春市| 西乌珠穆沁旗| 泽普县| 曲阳县| 二手房| 元江| 阜平县| 南投市| 桑植县| 方城县| 东海县| 上虞市| 综艺| 彭州市| 濮阳市| 营口市| 龙游县| 宾川县| 仁怀市|