7.4 Summary

This chapter covered Rust’s core control flow mechanisms, highlighting similarities and key differences compared to C:

  • Conditional Statements (if/else if/else):

    • Conditions must be bool; no implicit integer-to-boolean conversion.
    • Braces {} are mandatory for all blocks.
    • if can be used as an expression, requiring type consistency across branches. This often replaces C’s ternary operator (?:).
  • Pattern Matching (match):

    • A powerful construct replacing C’s switch.
    • Matches against complex patterns, not just constants.
    • Enforces exhaustiveness (all possibilities must be handled).
    • No fall-through behaviour; break is not needed between arms.
    • Can be used as an expression.
  • Looping Constructs:

    • loop: An infinite loop, breakable with break, which can return a value.
    • while: Condition-based loop checking the boolean condition before each iteration.
    • for: Iterator-based loop for ranges and collections, promoting safety over C-style index loops.
    • No direct do-while equivalent, but easily emulated with loop and break.
  • Loop Control:

    • break exits the current loop (optionally returning a value from loop).
    • continue skips to the next iteration.
    • Loop labels ('label:) allow break and continue to target specific outer loops in nested structures, providing clearer control than C’s goto or flag variables.

Rust’s control flow design emphasizes explicitness, type safety, and expressiveness. Features like match, expression-based if/loop, and labeled breaks help prevent common bugs found in C code and allow for more robust and readable programs. Mastering these constructs is essential for writing effective Rust code. The following chapters will build upon these foundations, particularly when exploring error handling and more advanced pattern matching.