codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🦀

Rust

9 / 58 topics
8Control Flow9If-Else Statements10Loops
Tutorials/Rust/If-Else Statements
🦀Rust

If-Else Statements

Updated 2026-04-20
3 min read

Introduction

If-Else statements are fundamental control structures used in programming to execute different blocks of code based on certain conditions. In Rust, these statements follow a syntax that emphasizes safety and explicitness, aligning with the language's philosophy of preventing common programming errors.

This tutorial will guide you through understanding how to use If-Else statements effectively in Rust, including their syntax, best practices, and real-world applications.

Basic Syntax

In Rust, an if statement checks a condition and executes a block of code if the condition is true. An optional else clause can be added to execute another block of code if the condition is false.

Example 1: Simple If-Else Statement

fn main() {
    let number = 3;

    if number < 5 {
        println!("condition was true");
    } else {
        println!("condition was false");
    }
}

Explanation:

  • The if keyword is followed by a condition (in this case, number < 5).
  • If the condition is true, the code inside the first block (println!("condition was true");) is executed.
  • If the condition is false, the code inside the else block (println!("condition was false");) is executed.

Example 2: Multiple Else-If Conditions

fn main() {
    let number = 6;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
}

Explanation:

  • Multiple else if conditions can be chained to check multiple scenarios.
  • The first condition that evaluates to true will execute its corresponding block, and the rest of the conditions are skipped.

Best Practices

1. Use Boolean Expressions

Always ensure that the condition in an if statement is a boolean expression. Rust does not implicitly convert non-boolean types to booleans.

// Incorrect: This will cause a compilation error
let x = 5;
if x { // Error: expected `bool`, found integer
    println!("x is true");
}

Correct Approach:

let x = 5;
if x != 0 {
    println!("x is not zero");
}

2. Handle All Possible Cases

When using multiple else if conditions, ensure that all possible cases are covered to avoid unexpected behavior.

fn main() {
    let number = 7;

    if number % 4 == 0 {
        println!("number is divisible by 4");
    } else if number % 3 == 0 {
        println!("number is divisible by 3");
    } else if number % 2 == 0 {
        println!("number is divisible by 2");
    } else {
        println!("number is not divisible by 4, 3, or 2");
    }
}

3. Use Early Returns for Complex Conditions

For complex conditions, consider using early returns to simplify the code and improve readability.

fn check_divisibility(number: i32) -> &'static str {
    if number % 4 == 0 {
        return "number is divisible by 4";
    } else if number % 3 == 0 {
        return "number is divisible by 3";
    } else if number % 2 == 0 {
        return "number is divisible by 2";
    }
    "number is not divisible by 4, 3, or 2"
}

fn main() {
    let result = check_divisibility(8);
    println!("{}", result);
}

Advanced Usage

If-Else as an Expression

In Rust, if statements are expressions and can return values. This makes them versatile for conditional assignments.

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

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

Explanation:

  • The if statement returns the value of the block that executes.
  • Both arms of the if must have the same type to ensure type safety.

Using If-Else with Loops

If-Else statements can be used within loops to control flow based on conditions.

fn main() {
    let mut counter = 0;

    while counter < 10 {
        if counter % 2 == 0 {
            println!("Even number: {}", counter);
        } else {
            println!("Odd number: {}", counter);
        }
        counter += 1;
    }
}

Explanation:

  • The if statement inside the loop checks whether the current value of counter is even or odd.
  • Depending on the result, a different message is printed.

Real-World Applications

Example 1: User Authentication

fn authenticate(username: &str, password: &str) -> bool {
    if username == "admin" && password == "secret" {
        true
    } else {
        false
    }
}

fn main() {
    let user = "admin";
    let pass = "secret";

    if authenticate(user, pass) {
        println!("Access granted");
    } else {
        println!("Access denied");
    }
}

Explanation:

  • The authenticate function checks the provided username and password against predefined values.
  • Based on the result, the main function prints an appropriate message.

Example 2: File Handling

use std::fs;

fn read_file(file_path: &str) -> Result<String, String> {
    if let Ok(contents) = fs::read_to_string(file_path) {
        Ok(contents)
    } else {
        Err("Failed to read file".to_string())
    }
}

fn main() {
    match read_file("example.txt") {
        Ok(content) => println!("File content: {}", content),
        Err(e) => println!("Error: {}", e),
    }
}

Explanation:

  • The read_file function attempts to read the contents of a file.
  • If successful, it returns the contents wrapped in an Ok.
  • If an error occurs, it returns an Err with an error message.

Conclusion

If-Else statements are essential for controlling program flow based on conditions. In Rust, their syntax is straightforward and aligns with the language's focus on safety and explicitness. By following best practices and understanding advanced usage, you can effectively use If-Else statements to build robust applications.

Remember, always ensure that your conditions are boolean expressions, handle all possible cases, and leverage the expressive power of if as an expression for cleaner code.


PreviousControl FlowNext Loops

Recommended Gear

Control FlowLoops