Rust Conditional Statements
In Rust, conditional statements have the following format:
Example
let number = 3;
if number < 5 {
println!("The condition is true");
} else {
println!("The condition is false");
}
}
In the above program there is a conditional if statement. This syntax is common in many other languages, but there are some differences: First, the condition expression `number < 5` does not need to be enclosed in parentheses (note: not needing it is not the same as not allowing it); however, Rust's `if` does not have the rule that a single statement can omit `{}`, and it does not allow using a single statement in place of a block. That said, Rust still supports the traditional else-if syntax:
Example
let a = 12;
let b;
if a > 0 {
b = 1;
}
else if a < 0 {
b = -1;
}
else {
b = 0;
}
println!("b is {}", b);
}
Run result:
b 为 1
In Rust, the conditional expression must be of type `bool`. For example, the following program is incorrect:
Example
let number = 3;
if number { // Error: expected `bool`, found integer rustc(E0308)
println!("Yes");
}
}
Although conditional expressions in C/C++ use integers, where non-zero means true, this rule is prohibited in many languages that emphasize code safety.
Combining the function body expressions we learned in the previous chapter, let's think about it:
if <condition> { block 1 } else { block 2 }
In this syntax, the{ block 1 }and{ block 2 }can it be a function body expression?
The answer is yes! That is, in Rust we can use if-else structures to achieve,(A ? B : C)the effect of a ternary conditional expression:
Example
let a = 3;
let number = if a > 0 { 1 } else { -1 };
println!(number is {}, number);
}
Run result:
number 为 1
Note: The types of the two function body expressions must be the same! And there must be an `else` followed by its expression block.
Other extensions