Salt la conținutul principal
eLearner.app
Modulul 2 · Lecția 1 din 23/14 în curs~12 min
Lecții din modul (1/2)

Condiționale și bucle

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

Exercițiu#rust.m2.l1.e1
Încercări: 0Se încarcă…

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

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări

Exercițiu#rust.m2.l1.e2
Încercări: 0Se încarcă…

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.

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări

Exercițiu#rust.m2.l1.e3
Încercări: 0Se încarcă…

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.

Se încarcă editorul...
Afișează indiciu

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

Soluție disponibilă după 3 încercări