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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.