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.

RustCli Tooling

Code

rustsnippet
32 lines
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

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.