expression

Stream CSV aggregation with row errors

Aggregate one row at a time and propagate invalid data and arithmetic overflow. Avoid collecting an entire large dataset when only a total is needed. Limit input and row size separately for untrusted streams. This example uses external crates; see the staged Cargo manifest. Expected stdout (not executed): 7 invalid row Common mistake: Silently dropping invalid rows and reporting an incomplete total as correct.

Formal Syntax & Structure

rust syntaxrust
for result in reader.deserialize::<Row>() { ... }

Working Example

Example Snippetrust
fn main() {    #[derive(serde::Deserialize)]    struct Row { qty: u64 }    fn total(input: &[u8]) -> Result<u64, &'static str> {        let mut r = csv::Reader::from_reader(input);        let mut sum = 0u64;        for result in r.deserialize::<Row>() {            let row = result.map_err(|_| "invalid row")?;            sum = sum.checked_add(row.qty).ok_or("overflow")?;        }        Ok(sum)    }    println!("{}", total(b"qty\n2\n5\n").unwrap());    println!("{}", total(b"qty\n2\nbad\n").unwrap_err());}
Rust Reference