Trim Input Before Parsing Numbers

Clean user input with trim and trim_end before parse, because stray whitespace and line endings are the most common reason valid numbers fail to parse.

RustForm Validation

Code

rustsnippet
23 lines
fn parse_port(raw: &str) -> Option<u16> {
    // trim 去掉两侧空白:空格、\t、\n、\r 全部处理
    let cleaned = raw.trim();
    if cleaned.is_empty() {
        return None;
    }
    cleaned.parse::<u16>().ok()
}

fn main() {
    let inputs = [" 8443 ", "8080\n", "\t9090\r\n", "", "not-a-port"];
    for raw in inputs {
        match parse_port(raw) {
            Some(port) => println!("{raw:?} -> {port}"),
            None => println!("{raw:?} -> invalid"),
        }
    }

    // trim_start/trim_end 只处理一侧:保留末尾缩进的场景用它
    let padded = "  value  ";
    println!("start-trimmed: {:?}", padded.trim_start());
    println!("end-trimmed: {:?}", padded.trim_end());
}

Inside the snippet

The working surface is the functions parse_port and main — everything else is wiring.

Repetition is confined to for raw in inputs — the rest of the file is straight-line. The match covers the value’s shapes one arm at a time — nothing falls to a default by accident.

Putting it to use

The primary signature is fn parse_port(raw: &str) -> Option<u16>

The demo output is labeled (start-trimmed:, end-trimmed:); each label names the call that printed it.

The demo flow inside main is parse_port — run the file to see it end to end.

Core lines

fn parse_port(raw: &str) -> Option<u16> {
    // trim 去掉两侧空白:空格、\t、\n、\r 全部处理
    let cleaned = raw.trim();
    if cleaned.is_empty() {
        return None;
    }
    cleaned.parse::<u16>().ok()
}
match parse_port(raw) {
    Some(port) => println!("{raw:?} -> {port}"),
    None => println!("{raw:?} -> invalid"),
}

Interactive Tools for This Topic

FAQ

What does Trim Input Before Parsing Numbers print when run?
No setup needed: run the file and look for labeled lines like `start-trimmed:`, `end-trimmed:` in the output.