Let Control Flow

Rust has a few control flow constructs which differ from other languages. They are used for pattern matching:

  • if let expressions
  • let else expressions
  • while let expressions

if let expressions

The if let expression lets you execute different code depending on whether a value matches a pattern:

  1. use std::time::Duration;
  2. fn sleep_for(secs: f32) {
  3.     if let Ok(duration) = Duration::try_from_secs_f32(secs) {
  4.         std::thread::sleep(duration);
  5.         println!("slept for {duration:?}");
  6.     }
  7. }
  8. fn main() {
  9.     sleep_for(-10.0);
  10.     sleep_for(0.8);
  11. }

let else expressions

For the common case of matching a pattern and returning from the function, use let else. The “else” case must diverge (return, break, or panic - anything but falling off the end of the block).

  1. fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> {
  2.     if let Some(s) = maybe_string {
  3.         if let Some(first_byte_char) = s.chars().next() {
  4.             if let Some(digit) = first_byte_char.to_digit(16) {
  5.                 Ok(digit)
  6.             } else {
  7.                 return Err(String::from("not a hex digit"));
  8.             }
  9.         } else {
  10.             return Err(String::from("got empty string"));
  11.         }
  12.     } else {
  13.         return Err(String::from("got None"));
  14.     }
  15. }
  16. fn main() {
  17.     println!("result: {:?}", hex_or_die_trying(Some(String::from("foo"))));
  18. }

Like with if let, there is a while let variant which repeatedly tests a value against a pattern:

  1. fn main() {
  2.     let mut name = String::from("Comprehensive Rust 🦀");
  3.     while let Some(c) = name.pop() {
  4.         println!("character: {c}");
  5.     }
  6.     // (There are more efficient ways to reverse a string!)
  7. }

Here String::pop returns Some(c) until the string is empty, after which it will return None. The while let lets us keep iterating through all items.

This slide should take about 10 minutes.

if-let

  • Unlike match, if let does not have to cover all branches. This can make it more concise than match.
  • A common usage is handling Some values when working with Option.
  • Unlike match, if let does not support guard clauses for pattern matching.

let-else

if-lets can pile up, as shown. The let-else construct supports flattening this nested code. Rewrite the awkward version for students, so they can see the transformation.

The rewritten version is:

  1. #![allow(unused)]
  2. fn main() {
  3. fn hex_or_die_trying(maybe_string: Option<String>) -> Result<u32, String> {
  4.     let Some(s) = maybe_string else {
  5.         return Err(String::from("got None"));
  6.     };
  7.     let Some(first_byte_char) = s.chars().next() else {
  8.         return Err(String::from("got empty string"));
  9.     };
  10.     let Some(digit) = first_byte_char.to_digit(16) else {
  11.         return Err(String::from("not a hex digit"));
  12.     };
  13.     return Ok(digit);
  14. }
  15. }

while-let

  • Point out that the while let loop will keep going as long as the value matches the pattern.
  • You could rewrite the while let loop as an infinite loop with an if statement that breaks when there is no value to unwrap for name.pop(). The while let provides syntactic sugar for the above scenario.