Review generated product summary

from Collections
Rust 1.98 advanced 6 min 4 issues to find

Review this generated product-summary helper.

Count product IDs, preserve first-seen order, return an error naming the index of any empty ID, avoid cloning repeated IDs during counting, and produce no output.

Rust
use std::collections::HashMap;

fn summarize(ids: &[String]) -> Result<Vec<(String, usize)>, String> {
    let mut counts: HashMap<String, usize> = HashMap::new();

    for (index, id) in ids.iter().enumerate() {
        if id.is_empty() {
            println!("empty product at {index}");
            continue;
        }

        *counts.entry(id.clone()).or_insert(0) += 1;
    }

    let mut rows: Vec<_> = counts.into_iter().collect();
    rows.sort_by(|left, right| left.0.cmp(&right.0));
    Ok(rows)
}

generated code is illustrative, not from any one model

Open in playground
Report an error