Learn about if-else conditionals in rust via examples.

Example 1: Branches and Loops

Learn about branches like if-else as well as loops in rust using this example.

Step 1: Create Project

  1. Open your Rust IDE.
  2. In the menu go to File --> Create New Project.

Step 2: Add Dependencies

Go to your Cargo.toml and modify it as follows:

[package]
name = "branches"
version = "0.1.0"
authors = ["Inanc Gumus <m@inanc.io>"]
edition = "2018"

[dependencies]

Step 3: Write Code

Next create a file known as main.rs and add the following code:

fn main() {
    // if expressions
    let number = 5;
    if number == 5 {
        println!("number is 5");
    } else if number == 4 {
        println!("number is 4");
    } else {
        println!("number is not 5");
    }

    // let + if
    let on = true;
    let n = if on { 1 } else { 0 };
    println!("n: {}", n);

    // loops
    let mut i = 0;
    loop {
        println!("is universe infinite?");
        i += 1;
        if i == 2 {
            break;
        }
    }

    // loop expressions
    let mut counter = 0;
    let result = loop {
        counter += 1;

        if counter == 2 {
            break counter + 1;
        }
    };
    println!("result: {}", result);

    // while loops
    let mut number = 3;
    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }
    println!("LIFTOFF!!!");

    // for loops
    let a = [1; 3];
    for e in a.iter() {
        println!("e: {}", e);
    }

    // rev()
    for n in (1..4).rev() {
        println!("{}!", n)
    }
    println!("boom!")
}

Here is the full code:

main.rs

fn main() {
    // if expressions
    let number = 5;
    if number == 5 {
        println!("number is 5");
    } else if number == 4 {
        println!("number is 4");
    } else {
        println!("number is not 5");
    }

    // let + if
    let on = true;
    let n = if on { 1 } else { 0 };
    println!("n: {}", n);

    // loops
    let mut i = 0;
    loop {
        println!("is universe infinite?");
        i += 1;
        if i == 2 {
            break;
        }
    }

    // loop expressions
    let mut counter = 0;
    let result = loop {
        counter += 1;

        if counter == 2 {
            break counter + 1;
        }
    };
    println!("result: {}", result);

    // while loops
    let mut number = 3;
    while number != 0 {
        println!("{}!", number);
        number -= 1;
    }
    println!("LIFTOFF!!!");

    // for loops
    let a = [1; 3];
    for e in a.iter() {
        println!("e: {}", e);
    }

    // rev()
    for n in (1..4).rev() {
        println!("{}!", n)
    }
    println!("boom!")
}

Run

Copy the code, build and run.

Reference

Here are the reference links:

Number Link
1. Download Example
2. Follow code author
3. Code: Apache 2.0 License

Categorized in: