What is Control Flow in Rust?
Description
- A control flow is an order in which the piece of program is executed.
- In control flow we have the following expressions:
- If expression
- Else expression
- Else if expression
If Expression:
- If expression permits to branch your code to any condition.
- If the condition is true then the program in if block will be executed.
- if when an expression is not true then the program would be passed to further blocks of else if expressions or else expression.
- The curly brackets which define the program blocks are called arms.
Else Expression:
- Else expression provides the program an alternative block of code to execute when the condition introduced in if block evaluates to false.
- Else expression comes at last.
Example
fn main() { let number = 3; if number <5 { println!("condition was true"); } else { println!("condition was false"); } }
Result:
Condition was true
Example
fn main() { let number = 7; if number <5 { println!("condition was true"); } else { println!("condition was false"); } }
Result:
Condition was false
Note:
- The condition introduced in if expression and else if expression should be bool type (true or false). Otherwise, the program will not run.
- Rust will not automatically try to convert non-Boolean types to a Boolean.
Example
fn main() { let number = 3; if number { println!("number was something other than zero"); } }
Result:
A compile-time error occurs.
Note:
Here Rust will give an error because instead of giving a bool condition we have placed an integer in condition.
Else If Expression:
- Else if the expression is used to introduce multiple conditions.
- This expression is always situated between if expression an else expression.
Example
fn main() { let number = 6; if number % 4 == 0 { println!("number is divisible by 4"); } else if number % 3 == 0 { println!("number is divisible by 3"); } else if number % 2 == 0 { println!("number is divisible by 2"); } else { println!("number is not divisible by 4, 3, or 2"); } }
Result:
The number is divisible by 4
Note:
- In the above example, there are two true conditions but Rust print the block of the first true condition.
- This means Rust only executes the block of the first true condition.
Using if inlet statement
- We can use if expression to store different values depending upon the condition in a variable using let statement, as mentioned in next example.
Example
fn main() { let condition = true; let number = if condition { 5 // (no semicolon means expression) } else { 6 // (no semicolon means expression) }; println!("The value of number is: { }", number); }
Note:
A value of 5 will be stored in the number variable.
Example
fn main() { let condition = true; let number = if condition { 5 } else { "six" }; println!("The value of number is: {}", number); }
Result:
Compile error will occur
Note:
Expression types are mismatched in each arm, hence an error will occur.