Return Values From Loops With break

Use loop as an expression: break hands a value out of the retry cycle, every break must agree on the type, and a budget arm supplies the fallback.

RustResilience

Code

rustsnippet
43 lines
use std::thread::sleep;
use std::time::Duration;

// simulates a loader that fails the first two attempts and succeeds on the third
fn try_load(attempt: u32) -> Result<&'static str, String> {
    match attempt {
        1 => Err("cache cold".to_string()),
        2 => Err("replica lagging".to_string()),
        _ => Ok("config v7"),
    }
}

fn main() {
    let mut attempt = 0;

    // loop is an expression: the value carried by break is the value of the whole loop
    let config = loop {
        attempt += 1;
        match try_load(attempt) {
            // success: break the value out
            Ok(config) => break config,
            Err(err) if attempt < 3 => {
                println!("attempt {attempt} failed: {err}; retrying");
                sleep(Duration::from_millis(10));
            }
            // budget exhausted: break with a fallback to avoid looping forever
            Err(err) => {
                println!("giving up after {attempt} attempts: {err}");
                break "defaults";
            }
        }
    };
    println!("loaded: {config}");

    // a loop that yields a value requires every break to agree on that type; a value-less loop has type ()
    let countdown = loop {
        attempt += 1;
        if attempt >= 5 {
            break attempt; // a different loop from the one above, with unrelated types
        }
    };
    println!("countdown reached: {countdown}");
}

What the code does

Return Values From Loops With break reduces to the functions try_load and main.

Failure is encoded in the return type — Result leaves no room for an unhandled error. Each possible shape of the input gets its own match arm, and the compiler checks the set is complete.

What to watch for

  • Every fallible call yields a Result you must unwrap or propagate; there is no implicit throw.

Applying it

Entry signature: fn try_load(attempt: u32) -> Result<&'static str, String>

Running the file prints labeled results such as attempt, giving up after, loaded: — each operation’s effect is visible in the output.

Launch the file; main takes over and steps through try_load.

Statements that matter

Err(err) if attempt < 3 => {
    println!("attempt {attempt} failed: {err}; retrying");
    sleep(Duration::from_millis(10));
}
Err(err) => {
    println!("giving up after {attempt} attempts: {err}");
    break "defaults";
}
fn try_load(attempt: u32) -> Result<&'static str, String> {
    match attempt {
        1 => Err("cache cold".to_string()),
        2 => Err("replica lagging".to_string()),
        _ => Ok("config v7"),
    }
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
Each fallible operation returns `Result`; nothing is silently discarded.
What does Return Values From Loops With break print when run?
Invoke the file as-is — the `attempt`, `giving up after`, `loaded:` prefixes identify which step printed each line.