Stdin Read Line With Parse Retry
Read stdin in a loop with read_line, clear and reuse one buffer, treat EOF as zero bytes, and match the parse Result so bad input retries instead of panicking.
Code
use std::io::{self, Write};
fn main() {
let mut buffer = String::new();
let mut attempts = 0u8;
loop {
print!("enter a port number: ");
io::stdout().flush().expect("flush failed");
// 复用同一块缓冲区:clear 只清内容,容量保留,不再重复分配
buffer.clear();
let bytes = io::stdin()
.read_line(&mut buffer)
.expect("failed to read stdin");
if bytes == 0 {
println!("stdin closed without a port");
break;
}
match buffer.trim().parse::<u16>() {
Ok(port) => {
println!("serving on port {port}");
break;
}
Err(_) => {
attempts += 1;
println!("not a valid port, attempt {attempts}");
}
}
}
}How the snippet works
Stdin Read Line With Parse Retry is built around the function main.
Branching goes through match, whose exhaustiveness checking turns forgotten cases into compile errors.
Applying it
Output lines are prefixed (stdin closed without a port, serving on port, not a valid port, attempt), making each step’s effect easy to spot.
Statements that matter
Ok(port) => {
println!("serving on port {port}");
break;
}
attempts += 1;
Interactive Tools for This Topic
HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Stdin Read Line With Parse Retry print when run?
- Invoke the file as-is — the `stdin closed without a port`, `serving on port`, `not a valid port, attempt` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.