Перейти до основного вмісту
eLearner.app
Модуль 2 · Урок 1 із 23/14 у курсі~12 min
Модульні уроки (1/2)

Умови та цикли

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

вправи#rust.m2.l1.e1
Спроби: 0Завантаження…

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!.

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб

вправи#rust.m2.l1.e2
Спроби: 0Завантаження…

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.

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб

вправи#rust.m2.l1.e3
Спроби: 0Завантаження…

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.

Завантаження редактора…
Показати підказку

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

Рішення доступне після 3 спроб