Control structures are a programming construct that allows you to control the flow of execution in your programs.
Control structures let you specify instructions to run only if certain conditions are met.
Rust Conditional Statements
Conditional statements are constructs that allow you to run code based on conditions.
Conditional statements come in handy for decision-making since the programs execution depends on whether the condition evaluates totrueorfalse.
Rust providesif,else, andmatchstatements for decision-making.
In Rust programs, theifstatement tests whether a certain condition evaluates to true.
If it does, the program runs the associated block of code.
Heres an example wherexisnt greater than 10, theifstatement evaluatesfalse, and anelsestatement runs.
Sincexis 5 and 5 isnt greater than 10, the program skips theifblock and executes theelseblock.
Match statements are similar toswitch statements in C#, Go, and C++.
Loops in Rust
Loops are a fundamental construct used for repetitive tasks likeweb scrapingand other automated actions.
Rust provides different types of loops, includingwhileloops,forloops, and thelooploop.
Before specifying the condition, youll specify while loops in Rust with thewhilekeyword.
The condition should be a boolean expression that determines the loops continuation.
When the condition evaluates false, the loop exits.
Heres an example of a Rust while loop that prints numbers from one to five.
The loop Loop
Theloopkeyword creates an infinite loop until you state an exit with thebreakkeyword.
The code in theloopblock will keep executing until the loop encounters abreakkeyword.
Heres an example of using thelooploop to print numbers one through five before specifying thebreakkeyword for the exit.
Themainfunction executes the loop, and theifstatement increments theivariable.
Theifstatement specifies the loop termination when theivariable exceeds five.
Rusts for Loops
In Rust, for loops iterate through a range or a collection of values.
Youll use theforkeyword to start a for loop, before specifying the range or collection it acts on.
The code block will execute once for each value in the sequence.
Heres an example of a for loop that prints values ranging from one through ten.
The loop iterates through the values from 1 to 10. you’re free to use thecontinuekeyword to skip values in for-loops.
Additionally, you might exit a for-loop with thebreakkeyword.
The loop terminates on encountering thebreakkeyword.
Theifstatement specifies that the loop should terminate when theivariable equals five.
Rust also provides structs.
Structs are data structures that group related values into a single object.