Lesson 17 — Process Control


This is the third day of my participation in the August More text Challenge. For details, see:August is more challenging

0x00 Review and opening

With the Rust data types out of the way for now, let’s start with process control in Rust. There are two ways to control the flow of code execution in Rust — conditional judgments and loops.

0x01 Conditional judgment

If expressions are common in any language and have the following form:

if condition1 {

block1

} else if condition2 {

block2

} else {

block3

}

All conditions are expressions of type bool. Unlike in C, Rust has a non-0 value that means true and a 0 value that means false. Condition curly braces are not required.

Let’s practice with a problem: Find a number of weeks. If you take a number mod seven, if it’s zero, it’s Sunday, and so on, if it’s six, it’s the sixth of the week.

The example code is as follows:

// Find a number corresponding to the week. Let week: u32 = 1; let week: u32 = 1; let week: u32 = 1; if week % 7 == 0 { println! (" You chose Sunday!" ) } else if week % 7 == 1 { println! (" You chose Monday!" ) } else if week % 7 == 2 { println! (" You chose Tuesday!" ) } else if week % 7 == 3 { println! (" You chose Wednesday!" ) } else if week % 7 == 4 { println! (" You chose Thursday!" ) } else if week % 7 == 5 { println! (" You chose Friday!" ) } else { println! (" You chose Saturday!" )}Copy the code

The code runs as follows:

You have chosen Monday!Copy the code

0 x02 cycle

A loop, as the name suggests, is the repeated execution of a piece of code. In Rust, there are three forms of loop: loop, while, for.. in.. Cycle. The loop is controlled by two statements: break and continue.

Break and continue

Both break and continue are used for loop control. Break is used to exit the loop directly, and continue is used to exit the loop from the current round. The code after continue is not executed, but it still performs the adjustment judgment again to determine whether to execute the next loop.

The loop cycle

It repeats, it never ends, and if there’s no exit condition, it’s an infinite loop. It’s easy to use.

Its signature form is:

loop {

// The code to execute the loop

}

The example code is as follows:

let mut count = 0; loop { count += 1; If count == 5 {break; } } println! ("count = {}", count);Copy the code

Code run result:

Loop -> count = 5Copy the code
The while loop

While is followed by an expression, and if the expression is true, the loop is executed.

The example code is as follows:

let mut count = 0; while count < 5 { count += 1; } println! ("while loop -> count = {}", count);Copy the code

Code run result:

While loop -> count = 5Copy the code
for.. in.. Cycle # # # # # #

Repeat the loop a specified number of times.

The example code is as follows:

let mut count = 0; for i in 1.. =5 { count = i } println! ("for.. in.. Loop -> count = {}", count);Copy the code

Code run result:

for.. in.. Loop -> count = 5Copy the code

The previous example code used break as an example, so let’s practice using continue. What is the final result of count when the following code runs?

The example code is as follows:

    let mut count = 1;
    while count < 5 {
        if count % 2 == 0 {
            count += 5;
            continue;
        }
        count += 1;
    }
Copy the code

Code run result:

continue test -> count = 7
Copy the code

Explanation:

The code starts with count set to 1, and then goes through the while loop, executing when count is less than 5.

Inside the loop, if count % 2 == 0, execute the condition block. And, of course, the first time through count == 1, obviously count % 2! Count == 2 (count += 1)

Count == 2 (count % 2 == 0); count += 5 (count == 7); continue (count == 7);

The third loop, count == 7, does not satisfy the condition that count < 5, exits the loop, and prints the value of count as 7.

0x03 match The mode is matched

match

In Rust, there are no switch statements for other languages. Instead, there is match pattern matching. Match is used to determine whether the current value matches one of a series of patterns. Patterns can be made up of literals, variables, and wildcards. Similar to switch in other languages, each pattern is a branch.

PS: In Rust, match pattern matching requires that all possibilities be exhausted, otherwise the program will report an error. You can add the _ wildcard at the end of a list of patterns to indicate all other patterns that are not specified (the Java equivalent of default).

The sample code looks like this (converting the first example to a match implementation) :

// Find a number corresponding to the week. Let week: u32 = 6 let week: u32 = 6 let week: u32 = 6; match week % 7 { 0 => { println! (" You chose Sunday!" ) } 1 => { println! (" You chose Monday!" ) } 2 => { println! (" You chose Tuesday!" ) } 3 => { println! (" You chose Wednesday!" ) } 4 => { println! (" You chose Thursday!" ) } 5 => { println! (" You chose Friday!" ) } 6 => { println! (" You chose Saturday!" ) } _ => { println! (" Unknown!" )}}Copy the code

Code run result:

You chose Saturday!Copy the code
If let and while let

Using match can be cumbersome in some cases, so if and while lets are also provided in Rust to replace match in some cases.

if let

If let:

if let pattern = expr {

block1

} else {

block2

}

When matching with an if let, note that pattern and expr are directly single = signs. To use the example at the beginning of this chapter, suppose I want to match only Friday and nothing else, we can use if let.

The example code is as follows:

let week: u32 = 5; if let 5 = week % 7 { println! (" You chose Friday!" ); } else { println! (" Unknown!" ); }Copy the code

Code run result:

You have chosen Friday!Copy the code
while let

The form of the while let is as follows:

while let pattern = expr {

block

}

Now I have a requirement that I output the values of the vectors in reverse order.

Using loop and match:

    let mut vec = vec![1, 3, 5, 7, 9];
    loop {
        match vec.pop() {
            None => {
                break;
            }
            Some(value) => {
                print!("{} ", value);
            }
        }
    }
Copy the code

While let

let mut vec = vec! [1, 3, 5, 7, 9]; while let Some(value) = vec.pop() { print! ("{} ", value); }Copy the code

Code run result:

match loop:
9 7 5 3 1 
while let:
9 7 5 3 1 
Copy the code

Obviously, the code modified by the while let is cleaner. It actually feels like the grammatical candy Rust gave us.

0 x04 summary

This section describes flow control, loop, and match. Finally, the use of while and if lets can simplify code in some scenarios. Comparatively speaking, this lesson is relatively simple and relaxed.

0x05 Source code for this section

017 · StudyRust – Code Cloud – Open Source China (gitee.com)

We’ll see in the next video — function.