Use a loop with a counter and Result propagation to retry a network request until it succeeds or the limit is reached.
use std::time::Duration;
use std::thread;
fn fetch_with_retry(url: &str, max_retries: u32) -> Result<String, String> {
let mut attempts = 0;
loop {
match fetch(url) {
Ok(data) => return Ok(data),
Err(e) => {
attempts += 1;
if attempts >= max_retries {
return Err(e);
}
thread::sleep(Duration::from_secs(1));
}
}
}
}
fn fetch(url: &str) -> Result<String, String> {
// Simulated network call
Err("Network error".to_string())
}