Char To Digit Input Validation
Parse user keystrokes with char::to_digit so each character is validated in radix before any arithmetic happens.
Code
// 逐字符 to_digit(radix):非该进制字符返回 None
fn parse_digits(input: &str) -> Option<Vec<u32>> {
input.chars().map(|c| c.to_digit(10)).collect()
}
fn sum_digits(input: &str) -> u32 {
parse_digits(input)
.map(|digits| digits.iter().sum())
.unwrap_or(0)
}
fn main() {
let attempts = ["2048", "20x8", "ff", ""];
for attempt in attempts {
match parse_digits(attempt) {
Some(digits) => println!("{attempt:?} -> {digits:?} sum {}", sum_digits(attempt)),
None => println!("{attempt:?} -> rejected"),
}
}
// 十六进制:to_digit(16) 接受 a-f 与 A-F
let hex: Vec<u32> = "DeAdBeEf".chars().map(|c| c.to_digit(16).unwrap()).collect();
println!("hex digits: {hex:?}");
}How it works
Char To Digit Input Validation comes down to the functions parse_digits, sum_digits and main.
A single loop drives the file — for attempt in attempts. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: fn parse_digits(input: &str) -> Option<Vec<u32>>
Running the file prints labeled results such as hex digits: — each operation’s effect is visible in the output.
Running the file executes main, which drives parse_digits and sum_digits in order.
Key statements
let hex: Vec<u32> = "DeAdBeEf".chars().map(|c| c.to_digit(16).unwrap()).collect();
.map(|digits| digits.iter().sum())
.unwrap_or(0)
}
input.chars().map(|c| c.to_digit(10)).collect()
}
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 Char To Digit Input Validation print when run?
- Running the file directly is enough — expect labeled output lines such as `hex digits:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.