Sling Academy
Home/Rust/Exploring `if`-`else if`-`else` Chains for Conditional Logic in Rust

Exploring `if`-`else if`-`else` Chains for Conditional Logic in Rust

Last updated: January 03, 2025

When it comes to making decisions in Rust, the if-else if-else statement is one of the fundamental tools. These conditional statements are used to control the flow of your program by executing certain pieces of code based on the evaluation of boolean expressions.

Basic Syntax of if-else

In Rust, the if expression can be thought of as a control flow keyword that allows your program to conditionally execute a block of code. The syntax starts with the if keyword followed by a condition in parentheses and a block of code that should execute if the condition is true.

fn main() {
    let number = 7;

    if number < 5 {
        println!("The number is less than 5.");
    }
}

In the above example, the program checks if the value of number is less than 5. If it is, it prints a message to the console. However, often you’ll need to evaluate more than two conditions, which is where else if chains are useful.

Chaining Conditions with else if

Using else if, we can handle many different possibilities. Let’s extend the previous example to handle different cases:

fn main() {
    let number = 7;

    if number < 5 {
        println!("The number is less than 5.");
    } else if number == 5 {
        println!("The number is exactly 5.");
    } else {
        println!("The number is greater than 5.");
    }
}

This usage allows us to handle multiple conditions more flexibly. The else if conditions are evaluated from top to bottom and as soon as one condition is true, that branch is executed. The else branch will only execute if all preceding conditions are false.

Practicing if-else Logic in Rust

Let’s go further with a practical example. Consider a program that categorizes numbers into size descriptors.

fn main() {
    let number = 23;

    if number < 0 {
        println!("{} is negative.", number);
    } else if number < 10 {
        println!("{} is small.", number);
    } else if number < 50 {
        println!("{} is medium.", number);
    } else {
        println!("{} is large.", number);
    }
}

In this example, based on the value of number, Rust will print out a string that represents the size category of the number. Such conditional logic is crucial for controlling how your programs behave in different scenarios.

Understanding if as Expressions

One unique aspect of Rust is that if can be used as an expression. This means you can assign the result of an if expression directly to a variable, thus keeping code concise:

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 10 };

    println!("The value of number is: {}", number);
}

Here, the number variable is assigned a value based on the condition. If condition evaluates to true, the value assigned is 5; if false, it's 10. This flexibility adds great expressiveness to the language.

What to Remember about if-else in Rust

  • if and else allow conditional execution of code blocks based on boolean expressions.
  • Use else if to handle multiple conditions efficiently.
  • Rust’s if is an expression, meaning it can return a value.
  • Always ensure conditions evaluate to a boolean value, as Rust enforces strong typing here.

With these fundamentals, you can apply conditional logic to control your program's flow and sculpt more dynamic and responsive Rust applications.

Next Article: Combining Boolean Expressions for Complex Conditions in Rust

Previous Article: Understanding Basic `if` Statements in Rust

Series: Control Flow in Rust

Rust

You May Also Like

  • E0557 in Rust: Feature Has Been Removed or Is Unavailable in the Stable Channel
  • Network Protocol Handling Concurrency in Rust with async/await
  • Using the anyhow and thiserror Crates for Better Rust Error Tests
  • Rust - Investigating partial moves when pattern matching on vector or HashMap elements
  • Rust - Handling nested or hierarchical HashMaps for complex data relationships
  • Rust - Combining multiple HashMaps by merging keys and values
  • Composing Functionality in Rust Through Multiple Trait Bounds
  • E0437 in Rust: Unexpected `#` in macro invocation or attribute
  • Integrating I/O and Networking in Rust’s Async Concurrency
  • E0178 in Rust: Conflicting implementations of the same trait for a type
  • Utilizing a Reactor Pattern in Rust for Event-Driven Architectures
  • Parallelizing CPU-Intensive Work with Rust’s rayon Crate
  • Managing WebSocket Connections in Rust for Real-Time Apps
  • Downloading Files in Rust via HTTP for CLI Tools
  • Mocking Network Calls in Rust Tests with the surf or reqwest Crates
  • Rust - Designing advanced concurrency abstractions using generic channels or locks
  • Managing code expansion in debug builds with heavy usage of generics in Rust
  • Implementing parse-from-string logic for generic numeric types in Rust
  • Rust.- Refining trait bounds at implementation time for more specialized behavior