Chuyển đến nội dung chính
eLearner.app
Mô-đun 2 · Bài học 1 trong tổng số 23/14 trong khóa học~12 min
Bài học theo mô-đun (1/2)

Điều kiện và vòng lặp

Control flow in Rust revolves around two main constructs: conditional expressions to decide which execution path to take, and loop constructs to repeat instructions.

Conditionals: if as an Expression

In Rust, the if statement is an expression, meaning it returns a value. We can use if to directly assign a value to a variable:

Code
let condition = true;
let number = if condition { 5 } else { 6 }; // if/else as an expression

Loops and Iterations

Rust provides three types of native loops: loop, while, and for.

1. loop (Infinite Loop)

The loop keyword creates an infinite loop that continues until you explicitly tell it to stop using break:

Code
let mut count = 0;
loop {
    count += 1;
    if count == 10 {
        break; // Exit the loop
    }
}

Additionally, you can return a value from a loop by placing it right after break:

Code
let result = loop {
    count += 1;
    if count == 10 {
        break count * 2; // Returns 20
    }
};

2. while (Conditional Loop)

Runs a block of code as long as a boolean condition remains true:

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

3. for (Iteration over Collections and Ranges)

The for loop is the most common and safest tool for iterating over elements in a collection or a range of numbers:

Code
// Iterates over numbers 1 through 3 (excluding 4)
for number in 1..4 {
    println!("Valore: {}", number);
}

// Iterates including the right boundary using '='
for number in 1..=3 {
    println!("Valore: {}", number); // Prints 1, 2 and 3
}

Loop Labels

When dealing with nested loops, break and continue statements apply to the innermost loop by default. Rust allows you to use a loop label (written as 'label_name:) to explicitly terminate or continue an outer loop:

Code
let mut count = 0;
'outer: loop {
    loop {
        if count == 5 {
            break 'outer; // Exits the outer loop directly
        }
        count += 1;
    }
}

Try it yourself

tập thể dục#rust.m2.l1.e1
Nỗ lực: 0Đang tải…

Declare a variable named number with a value of 7. Next, use an if/else expression to assign the value 'greater' to the variable message if number is greater than 5, or 'smaller' otherwise. Finally, print message using println!.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Write `let message = if number > 5 { 'greater' } else { 'smaller' };` and pass it to `println!`.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#rust.m2.l1.e2
Nỗ lực: 0Đang tải…

Write a for loop that prints the numbers from 1 to 5 inclusive (i.e. 1, 2, 3, 4, 5) using println! at each iteration.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use the inclusive range syntax `for i in 1..=5` and run `println!('{}', i);` inside the block.

Giải pháp khả dụng sau 3 lần thử

tập thể dục#rust.m2.l1.e3
Nỗ lực: 0Đang tải…

Write a loop that increments a mutable variable counter starting from 0. When counter reaches 10, exit the loop returning counter multiplied by 5 using the break statement to assign this value to an immutable variable result. Finally, print result.

Đang tải trình chỉnh sửa…
Hiển thị gợi ý

Use `let result = loop { ... };`. Inside the loop increment `counter` and add the condition `if counter == 10 { break counter * 5; }`.

Giải pháp khả dụng sau 3 lần thử