Conditional statements in the Rust language are in this format: There are conditions in the above procedure Running result: Conditional expressions in Rust must be Although conditional expressions in the Cripple + language are expressed as integers, either 0 or true, this rule is prohibited in many languages that pay attention to code security. Combined with the function body expressions learned in the previous chapter,we associate them with: Can the The answer is yes! That is, in Rust, we can use the if-else structure to implement expressions similar to ternary conditional operations Running result: Note: both function body expressions must be of the same type! And there must be one 7.9.1. Example #
fn main() { let number = 3; if number < 5 { println!("Condition is true"); } else { println!("Condition is false"); } } if statement, this syntax is common in many other languages, but there are some differences: first, conditional expressions number < 5 does not need to be included in parentheses (note that it is not allowed); but in Rust if there is no single sentence. {} is not allowed to use a statement instead of a block Nonetheless, Rust supports traditional else-if grammatical: 7.9.2. Example #
fn main() { let a = 12; let b; if a > 0 { b = 1; } else if a < 0 { b = -1; } else { b = 0; } println!("b is {}", b); } b is 1
bool type, for example, the following program is incorrect: 7.9.3. Example #
fn main() { let number = 3; if number { // Error reporting,expected \`bool`, found integerrustc(E0308) println!("Yes"); } } if <condition> { block 1 } else { block 2 }
{ block 1 } and { block 2 } in this syntax be function body expressions? (A ? B : C) effect: 7.9.4. Example #
fn main() { let a = 3; let number = if a > 0 { 1 } else { -1 }; println!("number 为 {}", number); } number is 1
else and the expression blocks that follow.