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

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.

主站蜘蛛池模板: 翁源县| 武夷山市| 大悟县| 利辛县| 镇原县| 彩票| 卓资县| 分宜县| 古丈县| 黄陵县| 湖州市| 灵璧县| 闽侯县| 鄄城县| 沐川县| 江达县| 姚安县| 郁南县| 顺昌县| 庐江县| 杭锦后旗| 昌图县| 定州市| 隆林| 义马市| 原平市| 靖西县| 涪陵区| 安福县| 漾濞| 邹平县| 青龙| 唐河县| 阿图什市| 南岸区| 曲阳县| 彭泽县| 西安市| 呼和浩特市| 华池县| 吴江市|