error-concept
Bounded retries with a deterministic operation
Limit total attempts, including the first call. Retry only a known transient failure for a repeat-safe operation. Return the final failure instead of looping forever. This fixture uses no real network or delays. Expected stdout (not executed): Ok(7); attempts=3 Expected stderr: (empty) Expected exit: success Common mistake: Confusing three attempts with three retries or retrying a permanent error.
Formal Syntax & Structure
rust syntaxrust
for attempt in 1..=max_attempts { ... }Working Example
Example Snippetrust
#[derive(Debug, PartialEq)]enum Failure { Temporary, Permanent }fn retry(mut op: impl FnMut() -> Result<u32, Failure>) -> Result<u32, Failure> { for attempt in 1..=3 { match op() { Err(Failure::Temporary) if attempt < 3 => continue, result => return result, } } unreachable!("fixed nonempty attempt range")}fn main() { let mut attempts = 0; let result = retry(|| { attempts += 1; if attempts < 3 { Err(Failure::Temporary) } else { Ok(7) } }); println!("{result:?}; attempts={attempts}");}