Conditional Statements in Rust

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we learn about using if-else statements in Rust. Similar to other programming languages, if-else statements in Rust don't require parentheses around the condition and each condition is followed by a block of code. These conditionals are expressions, so all branches must return the same type. Within the code example provided, we first check if the variable n is less than 0, and if so, it prints that n is negative. If n is not less than 0, we then check if it is greater than 0 and print that n is positive. Finally, if none of the previous conditions are met, we print that n is zero. Another example demonstrates how the if-else statement can be used as an expression to assign a new value to the variable big_n. If n is between -10 and 10, it prints that n is a small number and assigns 10 * n to big_n. Otherwise, it prints that n is a big number and assigns n / 2 to big_n. The final output of n and big_n is printed at the end.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/DataTypesGroup -.-> rust/integer_types("`Integer Types`") rust/DataTypesGroup -.-> rust/type_casting("`Type Conversion and Casting`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/variable_declarations -.-> lab-99303{{"`Conditional Statements in Rust`"}} rust/integer_types -.-> lab-99303{{"`Conditional Statements in Rust`"}} rust/type_casting -.-> lab-99303{{"`Conditional Statements in Rust`"}} rust/function_syntax -.-> lab-99303{{"`Conditional Statements in Rust`"}} rust/expressions_statements -.-> lab-99303{{"`Conditional Statements in Rust`"}} rust/lifetime_specifiers -.-> lab-99303{{"`Conditional Statements in Rust`"}} rust/operator_overloading -.-> lab-99303{{"`Conditional Statements in Rust`"}} end

if/else

Branching with if-else is similar to other languages. Unlike many of them, the boolean condition doesn't need to be surrounded by parentheses, and each condition is followed by a block. if-else conditionals are expressions, and, all branches must return the same type.

fn main() {
    let n = 5;

    if n < 0 {
        print!("{} is negative", n);
    } else if n > 0 {
        print!("{} is positive", n);
    } else {
        print!("{} is zero", n);
    }

    let big_n =
        if n < 10 && n > -10 {
            println!(", and is a small number, increase ten-fold");

            // This expression returns an `i32`.
            10 * n
        } else {
            println!(", and is a big number, halve the number");

            // This expression must return an `i32` as well.
            n / 2
            // TODO ^ Try suppressing this expression with a semicolon.
        };
    //   ^ Don't forget to put a semicolon here! All `let` bindings need it.

    println!("{} -> {}", n, big_n);
}

Summary

Congratulations! You have completed the If/Else lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like