DEV Community

Oludayo Adeoye
Oludayo Adeoye

Posted on

🦀 Rust Master Class - Chapter 4: Control Structures

🦀 Rust Master Class - Chapter 4: Control Structures


Three job offers. Three cities. I had to choose. Every if closes a door. Rust taught me that control flow isn't about code — it's about making decisions and living with them.


Rust control flow allows you to run specific code depending on whether a condition is true or to run code repeatedly while a condition is true . The primary tools for this are if expressions, match expressions, and loops .

1. If/Else Expressions

In Rust, if expressions execute code based on a Boolean condition . Unlike many other languages, if is an expression, meaning it can return a value that can be assigned to a variable .

  • Syntax: You can use if, else if, and an optional else block .
  • Condition Requirement: The condition must be a Boolean; providing other types will result in a compile-time error .

Code Example:

    // Create a new variable
let marks = 95;
    // Create a mutable variable
let mut grade = 'N';

if marks >= 90 {
    grade = 'Z';
} else if marks >= 80 {
    grade = 'B';
} else {
    grade = 'F';
}

// Using 'if' as an expression
    // Create a new variable
let status = if marks >= 50 { "Pass" } else { "Fail" }; 
Enter fullscreen mode Exit fullscreen mode

[Source: 228, 230, 284]

2. The match Expression

The match expression is a powerful control flow construct that allows you to compare a value against a series of patterns and execute code based on which pattern matches .

  • Exhaustiveness: match must cover all possible cases. The wildcard pattern _ is used to handle any values not specifically listed .
  • Patterns: You can match against specific values, multiple values using the pipe (|), or ranges using ..= .

Code Example:

    // Create a new variable
let marks = 98;
    // Create a new variable
let grade = match marks {
    90..=100 => 'Z', // Matches any value from 90 to 100 inclusive
    80..=89 => 'B',
    70..=79 => 'C',
    _ => 'F',        // Catch-all for any other value
};
Enter fullscreen mode Exit fullscreen mode

[Source: 232, 288, 371]

3. Loops

Rust provides three kinds of loops: loop, while, and for .

  • loop: Executes a block of code infinitely until you explicitly tell it to stop using a break statement .
  • while: Runs as long as a specified condition remains true .
  • for: The most common loop in Rust, used to iterate over a collection or a range of values .
  • break and continue: break exits the loop immediately, while continue skips the rest of the current iteration and starts the next one .

Code Example:

// Iterating over a range (0 to 9) in reverse
for i in (0..10).rev() {
    print!("{} ", i);
}

// Iterating over a vector
    // Create a new variable
let number_vec = vec![17-19];
for val in number_vec.iter() {
    // Output to console
    println!("Value: {}", val);
}
Enter fullscreen mode Exit fullscreen mode

[Source: 107, 243, 338]

4. Advanced Variants: if let

The if let syntax is a concise way to handle values that match one pattern while ignoring the rest . It is effectively "syntactic sugar" for a match that only cares about one case.

Code Example:

    // Create a new variable
let some_option = Some(3);
if let Some(3) = some_option {
    // Output to console
    println!("The value is three!");
}
Enter fullscreen mode Exit fullscreen mode

[Source: 230, 286]


📖 Download the full PDF: https://drive.google.com/file/d/1kKejduLtaagPPgCoPjfJEcS1jgY6O-Rr/view?usp=sharing

Part 4 of the Rust Master Class series — STEM EdTech | Automation Consulting | Rust Tutoring

RustLang #Programming #LearnToCode #STEM #EdTech


📚 Practice Resources

GitHub Repository: https://github.com/PacktPublishing/Rust-Programming-Master-Class-from-Beginner-to-Expert

Try it yourself: https://play.rust-lang.org/

Run the code from this chapter in the Rust playground, then clone the repo to continue your Rust journey!


Part 4 of the Rust Master Class series — STEM EdTech | Automation Consulting | Rust Tutoring

RustLang #Programming #LearnToCode #STEM #EdTech

Top comments (0)