Rust: Controlling the Flow – DEV Community
December 21, 2024

Rust: Controlling the Flow – DEV Community

Last time, at decide, decidewe looked at a way to add logic to a program through if and if else expressions. Next, we’ll look at how to further control the process through loops. Loops allow blocks of code to be repeated until some desired event or result occurs. There are three types of loops in Rust: loop, while, and for.


ring

The Loop keyword tells Rust to execute the same block of code over and over again until explicitly told to stop. Here is a basic example:

fn main() {
    loop {
        println!("Help, I'm stuck in a loop!");
    }
}
Enter full screen mode

Exit full screen mode

The program will continue to print the message “Help, I’m stuck in a loop!” on the console until you press Control-C to exit. This isn’t particularly elegant or useful. Fortunately, you can control how long you stay in the loop.

Here’s another example:

fn main() {
    let mut count = 10;
    loop {
        println!("Ok, in a loop, but will get out once the count reaches {}", count);
            count -= 1;
            if count < 0 {
                println!("Yay, I'm saved!");
                break;
            }
    }
}
Enter full screen mode

Exit full screen mode

We declare a counter variable and bind the starting value of 10 to it. Then, we enter a loop. Within the loop, we iterate through the following steps:

  • Print a message about being stuck in a loop
  • Decrement the counter value by one
  • Check if the counter is less than zero, if so we print a final message and then break out of the loop, terminating the program
  • If the counter is not less than zero, we loop again

Values ​​can be passed back outside the loop. This is useful when you might be calculating something and then need to pass the value back to the rest of the program. When you do this, you can assign the loop to a variable that will hold the results of the loop’s calculations. Here is an example:

fn main() {
    let mut counter = 0;

    let result = loop {
        counter += 1;

        if counter == 10 {
            break counter * 2;
        }
    };

    println!("The result is {}", result);
}
Enter full screen mode

Exit full screen mode

Here you can see that we join the final result of the counter variable into the break keyword and then bind the entire loop structure to the variable result.


although

Often, we need to repeat an action when a certain condition is true. If there is no other way, we can do this by combining the loops we just learned along with if, else, and break, however, this is cumbersome. Rust provides us with while loops.

Here is an example:

fn main() {
    let mut number = 10;
    while number != 0 {
        println!("Counting down...{}!", number);
        number -= 1;
    }

    println!("Liftoff!!!");
}
Enter full screen mode

Exit full screen mode

We declare a variable called number and bind the value 10 to it, and when we enter the while loop, we check that number is not equal to 0. . Eventually, we reach 0 and output the final message.


for

The last basic loop construct is the for loop. In a for loop, it is executed as many times as you specify. You must add any additional decision logic yourself. Without any other operations, the for loop will execute the specified number of times.

Suppose we have several arrays and we need to print all elements in each array. We can do this using a for loop.

fn main() {
    let array_one = [40, 80, 120];
    let array_two = [30, 70, 110];

    for array_item in array_one {
        println!("the value is: {}", array_item);
    }

    for array_item in array_two {
        println!("the value is: {}", array_item);
    }
}
Enter full screen mode

Exit full screen mode

This will loop through the individual entries in each array and print them to the console.

A convenient way to use a for loop is to import Range from the standard library and use the rev method available on Range to count down. Let’s do another countdown using this technique:

fn main() {
    for number in (1..10).rev() {
        println!("{}!", number);
    }
    println!("We have liftoff!!!");
}
Enter full screen mode

Exit full screen mode

This is quite elegant.


in conclusion

These loops, combined with decision-making logic such as if and else if, allow programs to have more complex execution sequences and be more flexible to internal and external inputs. These basic building blocks form the basis for everything you do with Rust. When combined with Rust’s more advanced features and data structures, you can create truly useful software. So far, my writing has covered the very basic programming concepts contained in Rust. Before I move on from the Rust Book to more advanced territory, in my next article I’ll demonstrate how to use everything I’ve written so far to build something simple. stay tuned!


refer to

The Rust Programming Language, Chapter 3.5

2024-12-21 21:22:09

Leave a Reply

Your email address will not be published. Required fields are marked *