Collect Parse Errors Per Line
Parse every line and collect the failures with their line numbers, so one pass reports all bad rows instead of the first.
Code
fn main() {
let rows = ["101,4", "102,x", "103,7", "y,1"];
// collect every bad line instead of stopping at the first failure
let mut failures: Vec<(usize, String)> = Vec::new();
for (line_no, row) in rows.iter().enumerate() {
let mut fields = row.split(',');
let id = fields.next().unwrap_or("");
let qty = fields.next().unwrap_or("");
let parsed = id
.parse::<u32>()
.and_then(|id| qty.parse::<u32>().map(|qty| (id, qty)));
match parsed {
Ok((id, qty)) => println!("line {}: id={} qty={}", line_no, id, qty),
Err(e) => failures.push((line_no, e.to_string())),
}
}
println!("failures: {}", failures.len());
for (line_no, err) in &failures {
println!("line {}: {}", line_no, err);
}
}How it works
Collect Parse Errors Per Line keeps everything in the function main.
A single loop drives the file — for (line_no, row) in rows.iter().enumerate(). A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.
What to watch for
- Any imports it has point exclusively at standard-library modules.
Putting it to use
Entry signature: fn main()
Each step the file takes is announced in the output: line, failures:.
The core lines, annotated
.and_then(|id| qty.parse::<u32>().map(|qty| (id, qty)));
let qty = fields.next().unwrap_or("");
let id = fields.next().unwrap_or("");
Interactive Tools for This Topic
FAQ
- What does Collect Parse Errors Per Line print when run?
- Invoke the file as-is — the `line`, `failures:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.