Parsing often combines splitting, trimming, and conversion while ignoring fields that do not match the target type.

Program

Play the program to choose a CSV line and sum the numeric fields.

line
csv_number_parser.rs
Replay: real traced execution (multi-file project)
fn main() {
    let line = "2,4,6";
    let total = parse_numbers(line);
    println!("total={total}");
}

fn parse_numbers(line: &str) -> i32 {
    line.split(',')
        .filter_map(|part| part.trim().parse::<i32>().ok())
        .sum()
}
fn main() {
    let line = "1, bad, 3";
    let total = parse_numbers(line);
    println!("total={total}");
}

fn parse_numbers(line: &str) -> i32 {
    line.split(',')
        .filter_map(|part| part.trim().parse::<i32>().ok())
        .sum()
}
fn main() {
    let line = "10,20";
    let total = parse_numbers(line);
    println!("total={total}");
}

fn parse_numbers(line: &str) -> i32 {
    line.split(',')
        .filter_map(|part| part.trim().parse::<i32>().ok())
        .sum()
}
  1. line ← "2,4,6"

    1fn main() {2    let lin→ "2,4,6"e = "2,4,6"; //@line="2,4,6", "1, bad, 3", "10,20"3    let total = parse_numbers(lin"2,4,6"e);4    println!("total={total}");
  2. total ← 12

    2    let line = "2,4,6"; //@line="2,4,6", "1, bad, 3", "10,20"3    let tota→ 12l = parse_numbers(lin"2,4,6"e);4    println!("total={total}");5}
    outputtotal=12
  1. line ← "1, bad, 3"

    1fn main() {2    let lin→ "1, bad, 3"e = "1, bad, 3";3    let total = parse_numbers(lin"1, bad, 3"e);4    println!("total={total}");
  2. total ← 4

    2    let line = "1, bad, 3";3    let tota→ 4l = parse_numbers(lin"1, bad, 3"e);4    println!("total={total}");5}
    outputtotal=4
  1. line ← "10,20"

    1fn main() {2    let lin→ "10,20"e = "10,20";3    let total = parse_numbers(lin"10,20"e);4    println!("total={total}");
  2. total ← 30

    2    let line = "10,20";3    let tota→ 30l = parse_numbers(lin"10,20"e);4    println!("total={total}");5}
    outputtotal=30
split `split(',')` creates fields from a comma-separated line.
filter_map `filter_map` keeps successfully parsed numbers and skips invalid fields.
sum `sum` folds the parsed numbers into one total.