Skip to content

Latest commit

 

History

History
124 lines (85 loc) · 3.97 KB

05. control_flow.md

File metadata and controls

124 lines (85 loc) · 3.97 KB

5. Control Flow: Conditional Statements and Loops

Conditional Statements: if, else if, else

Conditional statements in Rust allow you to execute different blocks of code based on certain conditions. The basic syntax for if statements is as follows:

let number = 10;

if number > 0 {
    println!("Number is positive");
} else if number < 0 {
    println!("Number is negative");
} else {
    println!("Number is zero");
}
  • The if statement checks the condition and executes the block of code if the condition is true.
  • The else if statement allows you to check additional conditions if the previous condition is false.
  • The else statement is optional and executes if none of the previous conditions are true.

Using if in a let Statement

In Rust, the if expression can be used on the right side of a let statement to conditionally assign a value to a variable. This allows for concise and readable code that assigns different values based on a condition. Example:

fn main() {
    let condition = true;
    let number = if condition { 5 } else { 6 };

    println!("The value of number is: {number}");
}

Pattern Matching with match

Pattern matching in Rust provides a concise way to compare values against a series of patterns and execute code based on the matched pattern. Here's an example:

let number = 42;

match number {
    0 => println!("Zero"),
    1 => println!("One"),
    _ => println!("Other"),
}
  • The match keyword is followed by the value to match against.
  • Each arm of the match consists of a pattern followed by the => operator and the code to execute if the pattern matches.
  • The _ wildcard pattern matches any value and is often used as a catch-all case.

Looping Constructs: loop, while, for

Rust provides several looping constructs for executing code repeatedly.

loop

The loop keyword creates an infinite loop that continues until explicitly interrupted with a break statement.

let mut counter = 0;

loop {
    println!("Counter: {}", counter);
    counter += 1;

    if counter >= 10 {
        break;
    }
}

NOTE: To return value in loop, you can add the value you want returned after the break expression you use to stop the loop; that value will be returned out of the loop. Example: break counter; in above example.

while

The while loop executes a block of code as long as the specified condition is true.

let mut counter = 0;

while counter < 10 {
    println!("Counter: {}", counter);
    counter += 1;
}
for

The for loop iterates over elements of an iterator.

let numbers = [1, 2, 3, 4, 5];

for number in numbers.iter() {
    println!("Number: {}", number);
}

Early Exit with break and continue

  • The break statement exits the current loop immediately.
  • The continue statement skips the rest of the current iteration and proceeds to the next iteration of the loop.

Iterating Over Collections with for Loop and Iterators

  • Rust's for loop is particularly useful for iterating over collections like arrays, vectors, and ranges.
  • You can also use iterators, which provide a powerful way to work with sequences of elements in Rust.

Best Practices

  • Use if, else if, and else for simple conditional branching, and match for more complex pattern matching scenarios.
  • Prefer for loops and iterators for iterating over collections, as they are more concise and idiomatic in Rust.
  • Use loop when you need to create an infinite loop with explicit exit conditions.

Real-World Example

Imagine you're developing a text adventure game in Rust. You use conditional statements to handle different player choices and looping constructs to manage game flow and interactions.

Conclusion

Understanding control flow constructs in Rust is essential for writing expressive and efficient code. By mastering these concepts, you'll have the tools to build complex algorithms and applications with confidence.