In Rust, the if expression is a control flow structure used to execute code based on conditions. Unlike many other languages, Rust's if can return a value, making it very flexible and powerful.
Basic Syntax
The basic syntax of Rust's if expression is: if condition { code block }. The condition must be of boolean type (bool), otherwise the compiler will report an error. The following example shows how to use the if expression to check if a number is positive.
let number = 5;
if number > 0 {
println!("The number is positive");
}
Note: In Rust, conditions do not need to be enclosed in parentheses, but the code block must be surrounded by curly braces {}.
Using else and else if
You can use else and else if to handle multiple conditions; there can be multiple else if branches, but only one else branch. The following example demonstrates how to print different messages based on whether a number is positive, negative, or zero.
let number = -3;
if number > 0 {
println!("Positive");
} else if number < 0 {
println!("Negative");
} else { // Executes the else branch when all conditions do not match
println!("Zero");
}
At most, only one branch will be executed, and after executing one branch, other branches will not be executed:
let x = 10;
if x > 5 {
println!("Branch A"); // This executes
} else if x > 8 {
println!("Branch B"); // ❌ Will not execute (condition is true, but it is mutually exclusive)
} else {
println!("Branch C"); // ❌ Will not execute
}
if Expression Returning a Value
Rust's if expression can return a value, allowing you to use it in assignments. Each branch must return a value of the same type. The following example shows how to use the if expression to assign a string.
let condition = true;
let result = if condition {
"Condition is true"
} else {
"Condition is false"
};
println!("{}", result); // Output: Condition is true
When if is used as an expression, it must have an else branch.
Note: If the branches of an if expression return different types, the compiler will report an error. For example, if true { 1 } else { "two" } will cause a type mismatch error.
Nested if Expressions
You can nest other if expressions within an if expression to handle more complex logic. The following example shows how to check if a number is within a specific range.
let x = 10;
if x > 0 {
if x < 20 {
println!("x is between 0 and 20");
}
}