Page Content

Tutorials

Rust if multiple conditions with Examples

if Expressions

An if expression allows branching code depending on conditions. Provide a condition, which must evaluate to a single Boolean value (true or false). If the condition is true, the block of code immediately following the condition is executed. The block is skipped if the condition is false.

Unlike other languages where if represents a statement, Rust uses if as an expression. Expressions in Rust produce a value.

The basic syntax is:

if condition {// true block }

You can combine if with an else block to provide an alternative block of code to execute if the condition evaluates to false. If you don’t provide an else block and the condition is false, the program skips the if block and continues with the next code.

The syntax for if else is:

 if condition { 
// true block 
} 
else {
 // false block 
}

Example:

fn main() { 
let x = 6;
let y = 8;
if x>y {
    println!("correct");
}
 else {
    println!("wrong");
}
}

Outupt:

Wrong

In the above example, the x variable is compared to y. The result of this comparison (false in this case) is used as the conditional expression for the if. Because it’s false, the else block is executed, printing “Wrong”.

else If

Optionally, you can include one or more else if expressions after the initial if. An else if is a nested if. If there are multiple else if expressions, we evaluate them in order. The block associated with the first else if condition that evaluates to true is executed. An else block, if present, must follow all else if blocks and acts as the default behaviour if none of the preceding if or else if conditions are true. Using too many else if expressions can clutter code, and it might be better to refactor using a match expression in such cases.

The syntax for else if is:

if condition {
 // true block 
}
 else if condition {
 // nested true block
 } 
else { 
// false block
 }

Example:

fn main() { 
let x = 6;
let y = 6;
if x>y {
    println!("correct");
} else if x==y{
    println!("Both are equals");
}
else{
     println!("Wrong");
}
}

Output:

Both are equals

In the example above, we compare x against Y. The first condition is not correct; then go to the second condition; it is correct. The final output is “Both are equals.” If the second condition is not correct, the output is “wrong”.

if as an Expression with Return Value

Since if is an expression, it can return a value. The value of the if expression is the value of the last expression in the block that is executed. All blocks within an if expression (including else and else if) must return a reliable type. If a block doesn’t clearly return a value (e.g., the last line is a statement ending with a semicolon), the default return is the empty tuple (). For an if expression to have a value, it  requires an else branch to ensure all paths yield a value.

Example:

fn main() { 
let x = 2;
let y = if x>5{
          8
}
else{
        9
};
print!("{}",y)
}

Output:

9

In the above example, the if expression returns either 8 or 9 based on the x variable, and this value is assigned to the y variable.

if let Expressions

The if let expression is a variation of the if statement that uses pattern matching to determine the control path instead of using a Boolean conditional expression. If the pattern matches, we execute the associated block; otherwise, we skip it. else and else if can also be used with if let.

if let is seen as syntax sugar for a match expression only runs code when the value matches one specific pattern and ignores all other possibilities. It’s a convenient and concise expression for handling  types where you only care about a single variant or pattern.

The syntax for if let with optional else is:

 if let pattern = expression { 
// pattern matches
} 
else { 
// pattern does not match (optional) 
}

An else block used with if let corresponds to the _ (wildcard) case in the equivalent match expression. if, else if, and if let can be intermixed.

A key difference between if let and a comprehensive match expression is  the compiler does not check for exhaustiveness with if let. If you omit an else block and miss handling some cases, the compiler won’t alert you to the logic bug.

Example:

fn main() { 
let z = Some(5);
if let Some(y) = z {
    // The pattern Some(y) matches z (which is Some(5))
    // The underlying value 5 is bound to 'result'
    println!("Matched Some with value: {}", y);
} else {
    // This block executes if option_value were None or didn't match
    println!("Pattern did not match");
}
}

Output:

Matched Some with value: 5

In the above example, the Some(y) pattern is matched against z. being Some(5), matching the pattern, binding 5 to the result, and executing the if block. If z had been None, the pattern would not match, leading to the execution of the else block.

Like if expressions, if let statements also evaluate to a value determined by the executed block.

Index