Loading...
Loading...

Rust Control Structures

Control Structures are programming constructs that determine the flow of execution in a Rust program. They include conditional branching (if/else), looping (for/while/loop), and pattern matching (match). Unlike many languages, Rust's control structures are expressions that can return values, enabling more concise and functional-style code while maintaining strict type safety and exhaustive pattern checking.

1. If Expressions

Key Points:

  • No parentheses around conditions (unlike C/Java)
  • Returns a value (can be assigned)
  • Type consistency required in all branches
// Basic if-else
let number = 7;
if number < 5 {
    println!("Condition was true");
} else {
    println!("Condition was false");
}

// If as expression
let result = if number % 2 == 0 {
    "even"
} else {
    "odd"
};
println!("The number is {}", result);

If Quiz

What's wrong with this code?

let x = if true { 1 } else { "two" };
  • Missing semicolon
  • Type mismatch between branches
  • Parentheses needed around condition

2. Looping Constructs

Loop (Infinite)

let mut count = 0;
loop {
    count += 1;
    if count == 3 {
        break count * 2; // Returns value
    }
};

While

let mut number = 3;
while number != 0 {
    println!("{}!", number);
    number -= 1;
}

For (Range-based)

for i in 1..4 { // 1 to 3
    println!("{}", i);
}

// Iterating collections
let arr = [10, 20, 30];
for num in arr.iter() {
    println!("{}", num);
}

Loop Quiz

Which loop is guaranteed to run at least once?

  • while loop
  • loop (infinite)
  • for loop

3. Match Expressions

Rust's supercharged switch statement:

  • Exhaustive checking (must cover all cases)
  • Pattern matching capabilities
  • Can return values
let coin = Coin::Quarter(UsState::Alaska);
match coin {
    Coin::Penny => {
        println!("Lucky penny!");
        1
    },
    Coin::Nickel => 5,
    Coin::Dime => 10,
    Coin::Quarter(state) => {
        println!("Quarter from {:?}!", state);
        25
    },
}

// Matching with ranges
match temperature {
    0..=32 => "freezing",
    33..=50 => "cold",
    51..=70 => "mild",
    _ => "hot", // Default case
}

Match Quiz

What happens if you omit the _ case when matching numbers?

  • It defaults to 0
  • Compile error (non-exhaustive patterns)
  • Runtime panic

4. Concise Control with if let

For matching one pattern while ignoring others

let some_value = Some(3);

// Verbose match
match some_value {
    Some(3) => println!("three"),
    _ => (),
}

// Equivalent if let
if let Some(3) = some_value {
    println!("three");
}

If Let Quiz

When should you use if let instead of match?

  • When you need exhaustive checking
  • When you only care about one pattern
  • When working with integers

5. while let Pattern Matching

Loop until pattern fails to match

let mut stack = vec![1, 2, 3];

while let Some(top) = stack.pop() {
    println!("{}", top);
}
// Prints 3, 2, 1

While Let Quiz

What does while let Some(x) = iterator.next() do?

  • Runs once if iterator has items
  • Loops until iterator returns None
  • Matches only the first item

6. Early Returns and ? Operator

Early Return

fn divide(a: i32, b: i32) -> Option<i32> {
    if b == 0 {
        return None; // Early exit
    }
    Some(a / b)
}

? Operator (Error Propagation)

fn read_file() -> Result<String, io::Error> {
    let mut f = File::open("file.txt")?; // Returns error if fails
    let mut s = String::new();
    f.read_to_string(&mut s)?;
    Ok(s)
}

Error Handling Quiz

What does the ? operator do?

  • Terminates the program
  • Returns the error early from function
  • Converts errors to strings
0 Interaction
0 Views
Views
0 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home