Getting Started with Rust Code (Part 5)

Getting Started with Rust Code (Part 5)

This article mainly explains the control flow and iterators in Rust’s basic syntax. The control flow section covers conditional branches, loops, pattern matching, etc., while the iterators section progresses from basic concepts to custom iterators, explained step by step.

During your learning process, don’t get too caught up in the details. There may be parts you don’t understand yet, which we haven’t covered. It’s okay to read through it first; as you continue learning, you’ll have moments of clarity!

Control Flow

1. Conditional Branching <span>if</span>

Basic Usage

fn main() {
    let x = 5;

    if x > 0 {
        println!("x is positive");
    } else if x < 0 {
        println!("x is negative");
    } else {
        println!("x is zero");
    }
}

📌 Note: In Rust, <span>if</span> is an expression and can directly return a value.

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 10 };
    println!("number = {}", number); // 5
}

⚠️ Both branches must return the same type, otherwise a compilation error will occur.

2. Loops

Rust has three main types of loops:

1. <span>loop</span> Infinite Loop

fn main() {
    let mut count = 0;
    loop {
        count += 1;
        if count == 3 {
            println!("Exiting the loop");
            break;
        }
    }
}
  • <span>break</span> Exit the loop
  • <span>continue</span> Skip this iteration

You can also make <span>loop</span>return a value:

fn main() {
    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 5 {
            break counter * 2; // break followed by a value
        }
    };
    println!("result = {}", result); // 10
}

2. <span>while</span> Conditional Loop

fn main() {
    let mut n = 3;
    while n > 0 {
        println!("Countdown: {}", n);
        n -= 1;
    }
    println!("Launch!");
}

3. <span>for</span> Iteration Loop

<span>for</span> is commonly used to iterate over ranges or collections.

fn main() {
    // Iterate over a range
    for i in 1..5 {   // from 1 to 4
        println!("{}", i);
    }

    // Iterate over an array
    let arr = [10, 20, 30];
    for val in arr {
        println!("Value = {}", val);
    }
}

📌 <span>1..5</span> is a half-open range (excluding 5); <span>1..=5</span> is a closed range (including 5).

3. Pattern Matching <span>match</span>

Rust’s <span>match</span> is more powerful than the <span>switch</span> in other languages, allowing for pattern matching.

fn main() {
    let number = 2;

    match number {
        1 => println!("One"),
        2 | 3 => println!("Two or Three"), // Multiple patterns
        4..=6 => println!("Between 4 and 6"), // Range
        _ => println!("Other number"),       // Wildcard
    }
}

<span>if let</span> and <span>while let</span>

When only one matching pattern is of interest, you can simplify using <span>if let</span>:

fn main() {
    let some_num = Some(7);

    if let Some(x) = some_num {
        println!("Matched {}

Leave a Comment