Rust Conditional Statements
Conditional statements in Rust are written in this format:
Example
fn main() {
let number = 3;
if number < 5 {
println!("Condition is true");
} else {
println!("Condition is false");
}
}
In the above program, there is an if statement, which 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 needed does not mean not allowed); however, Rust's if does not have the rule where a single statement does not need curly braces {}
, and it does not allow a single statement to replace a block. Nevertheless, Rust still supports the traditional else-if syntax:
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);
}
Output:
b is 1
In Rust, the condition expression must be of type bool. For example, the following program is incorrect:
Example
fn main() {
let number = 3;
if number { // Error, expected `bool`, found integer rustc(E0308)
println!("Yes");
}
}
Although in C/C++ languages, the condition expression is represented by an integer, where non-zero means true, this rule is prohibited in many languages that focus on code safety.
Considering the function body expressions we learned in previous chapters, we can think about this:
if <condition> { block 1 } else { block 2 }
Can { block 1 } and { block 2 } be function body expressions?
The answer is yes! This means that in Rust, we can use if-else structures to achieve effects similar to the ternary conditional operator (A ? B : C):
Example
fn main() {
let a = 3;
let number = if a > 0 { 1 } else { -1 };
println!("number is {}", number);
}
Output:
number is 1
Note: Both function body expressions must be of the same type! And there must be an else followed by an expression block.