Control flow is a fundamental concept in programming that allows you to determine which parts of your code execute based on specific conditions. This concept is key for writing dynamic and efficient programs. In Rust, control flow is managed using conditional statements such as if, else if, and else. Below, we explore these constructs with clear examples.Documentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
The if Statement
The if statement is the most basic control flow construct. It executes a block of code only when a given condition evaluates to true. The syntax is as follows:The else Statement
The else statement offers an alternative code block that executes when the condition in the if statement is false. For example, in the following code, the number is set to 15:The else if Statement
To evaluate multiple conditions sequentially, you can use the else if statement. As soon as a condition evaluates to true, its corresponding block is executed, and the remaining conditions are skipped. The syntax is:number < 10) and the second condition (number < 20) are false, so the else block executes, and the output is:
The number is 20 or greater
Combining Conditions
You can build more complex conditional statements by combining multiple conditions with logical operators like AND (&&) and OR (||).In Rust, combining conditions allows you to create highly specific checks. For example, use the && operator to ensure multiple conditions are true before executing a block.
Using if in a let Statement
Rust also permits using an if expression to assign a value to a variable. This feature streamlines conditional assignments. Consider the following example:number is assigned a value of 5. If the condition were false, number would be assigned 10. The output of this execution is:
The value of number is: 5
Summary
In this overview, we covered the following control flow structures in Rust:- if statements: Execute a block of code if a condition is true.
- else statements: Provide an alternative block of code when the if condition is false.
- else if statements: Allow checking multiple conditions sequentially.
- Combining conditions: Use logical operators to create more complex conditionals.
- Using if in a let statement: Conditionally assign values to variables in a concise manner.