Rust Playbook

Course › Week 3 · Iterators, real data, speed › Day 7 · lesson 21 of 42 · 20 min reading + 1–2 h practice

Week 3 checkpoint

Flat memory on a 1M-row file, and bad rows never stop the run.

iteratorsstreaming

On this page
  1. 1. Only one error reported
  2. 2. Reading a counter the closure is changing
  3. 3. Pushing results from every core
  4. 4. The field Laravel leaves out
  5. 5. Eight rows in, six rows out
  6. The csv2json exit check
  7. What PHP would have done
  8. Remember

Five problems from this week. Two do not compile. Three compile and run and give the wrong answer, which is the kind of bug iterators, batches and parallel code invite. As before: write your one-sentence explanation first, then open the answer.

1. Only one error reported

The import should list every bad score so the school can fix them all at once. It reports one:

src/main.rs
fn parse_scores(inputs: &[&str]) -> Result<Vec<u8>, String> {
    inputs
        .iter()
        .map(|input| input.parse::<u8>().map_err(|e| format!("'{input}': {e}")))
        .collect()
}

fn main() {
    match parse_scores(&["5", "four", "3", "", "2"]) {
        Ok(scores) => println!("scores: {scores:?}"),
        Err(error) => println!("rejected: {error}"),
    }
}
$ cargo run
rejected: 'four': invalid digit found in string
Show the solution

One sentence: collecting into a Result stops at the first Err by design, which is right for a form and wrong for an import that must report everything.

The fix: keep both outcomes. A loop with match sends each item to the right list; nothing stops early.

src/main.rs
fn parse_scores(inputs: &[&str]) -> (Vec<u8>, Vec<String>) {
    let mut scores: Vec<u8> = Vec::new();
    let mut errors: Vec<String> = Vec::new();
    for input in inputs {
        match input.parse::<u8>() {
            Ok(score) => scores.push(score),
            Err(e) => errors.push(format!("'{input}': {e}")),
        }
    }
    (scores, errors)
}

fn main() {
    let (scores, errors) = parse_scores(&["5", "four", "3", "", "2"]);
    println!("scores: {scores:?}");
    for error in &errors {
        println!("rejected: {error}");
    }
}
$ cargo run
scores: [5, 3, 2]
rejected: 'four': invalid digit found in string
rejected: '': cannot parse integer from empty string

Returning a pair (Vec<u8>, Vec<String>) is enough here. csv2json does the same thing as a stream, writing each outcome as it happens instead of keeping two lists.

2. Reading a counter the closure is changing

src/main.rsdoes not compile
fn main() {
    let mut rejected: u32 = 0;
    let mut reject = |line: u64, reason: &str| {
        rejected += 1;
        eprintln!("line {line}: {reason}");
    };

    reject(5, "score is not a number");
    println!("{rejected} rejected so far");
    reject(9, "missing fields");
}
cargo build
error[E0502]: cannot borrow `rejected` as immutable because it is also borrowed as mutable
  --> src/main.rs:9:16
   |
 3 |     let mut reject = |line: u64, reason: &str| {
   |                      ------------------------- mutable borrow occurs here
 4 |         rejected += 1;
   |         -------- first borrow occurs due to use of `rejected` in closure
...
 9 |     println!("{rejected} rejected so far");
   |                ^^^^^^^^ immutable borrow occurs here
10 |     reject(9, "missing fields");
   |     ------ mutable borrow later used here

For more information about this error, try `rustc --explain E0502`.
error: could not compile `hello` (bin "hello") due to 1 previous error
Show the solution

One sentence: the closure holds a mutable borrow of rejected for as long as it may still be called, so nobody else can read rejected until its last call.

The fix: read the counter after the last call (the borrow ends there, as in the borrowing lesson). If you really need the count in the middle, keep the counter outside the closure and have the closure return something instead.

src/main.rs
fn main() {
    let mut rejected: u32 = 0;
    let mut reject = |line: u64, reason: &str| {
        rejected += 1;
        eprintln!("line {line}: {reason}");
    };

    reject(5, "score is not a number");
    reject(9, "missing fields");
    println!("{rejected} rejected");
}
$ cargo run
2 rejected
line 5: score is not a number
line 9: missing fields

3. Pushing results from every core

src/main.rsdoes not compile
use rayon::prelude::*;

fn main() {
    let comments = vec!["Too  FAST!!", "Clear, thank you.", "ok"];
    let mut cleaned: Vec<String> = Vec::new();

    comments
        .par_iter()
        .for_each(|c| cleaned.push(c.to_lowercase()));

    println!("{cleaned:?}");
}
cargo build
error[E0596]: cannot borrow `cleaned` as mutable, as it is a captured variable in a `Fn` closure
 --> src/main.rs:9:23
  |
5 |     let mut cleaned: Vec<String> = Vec::new();
  |         ----------- `cleaned` declared here, outside the closure
...
9 |         .for_each(|c| cleaned.push(c.to_lowercase()));
  |          -------------^^^^^^^------------------------
  |          |        |   |
  |          |        |   cannot borrow as mutable
  |          |        in this closure
  |          expects `Fn` instead of `FnMut`

For more information about this error, try `rustc --explain E0596`.
error: could not compile `hello` (bin "hello") due to 1 previous error
Show the solution

One sentence: two cores pushing into the same Vec at once would corrupt it, so rayon only accepts closures that read what they capture.

The fix: do not share the Vec; let rayon build it. map then collect gives one Vec, in the input order.

src/main.rs
use rayon::prelude::*;

fn main() {
    let comments = vec!["Too  FAST!!", "Clear, thank you.", "ok"];

    let cleaned: Vec<String> = comments.par_iter().map(|c| c.to_lowercase()).collect();

    println!("{cleaned:?}");
}
$ cargo run
["too  fast!!", "clear, thank you.", "ok"]

4. The field Laravel leaves out

The Laravel API omits comment when it is empty (its resource uses whenNotNull). The Rust side was written against an example that had one:

src/main.rs
use serde::Deserialize;

#[derive(Deserialize)]
struct Answer {
    evaluation_id: u64,
    score: u8,
    comment: String,
}

fn main() {
    let payloads = [
        r#"{"evaluation_id": 1001, "score": 5, "comment": "Clear explanations"}"#,
        r#"{"evaluation_id": 1002, "score": 3}"#,
    ];
    for json in payloads {
        match serde_json::from_str::<Answer>(json) {
            Ok(a) => println!("#{}: {} {:?}", a.evaluation_id, a.score, a.comment),
            Err(error) => println!("rejected: {error}"),
        }
    }
}
$ cargo run
#1001: 5 "Clear explanations"
rejected: missing field `comment` at line 1 column 35
Show the solution

One sentence: a String field is required, so a payload without it is rejected, though the API contract says the comment is optional.

The fix: say what the contract says: Option<String>. A missing key and "comment": null both become None (the serde lesson). The type now documents the contract for the next reader.

src/main.rs
use serde::Deserialize;

#[derive(Deserialize)]
struct Answer {
    evaluation_id: u64,
    score: u8,
    comment: Option<String>,
}

fn main() {
    let payloads = [
        r#"{"evaluation_id": 1001, "score": 5, "comment": "Clear explanations"}"#,
        r#"{"evaluation_id": 1002, "score": 3}"#,
    ];
    for json in payloads {
        match serde_json::from_str::<Answer>(json) {
            Ok(a) => println!("#{}: {} {:?}", a.evaluation_id, a.score, a.comment),
            Err(error) => println!("rejected: {error}"),
        }
    }
}
$ cargo run
#1001: 5 Some("Clear explanations")
#1002: 3 None

5. Eight rows in, six rows out

The batching loop compiles, passes a test with 6 rows, and loses data on real files:

src/main.rs
const BATCH: usize = 3;

fn main() {
    let rows = ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"];
    let mut written: Vec<&str> = Vec::new();

    let mut batch: Vec<&str> = Vec::with_capacity(BATCH);
    for row in rows {
        batch.push(row);
        if batch.len() == BATCH {
            written.extend(&batch);
            batch.clear();
        }
    }

    println!(
        "{} rows in, {} rows out: {written:?}",
        rows.len(),
        written.len()
    );
}
$ cargo run
8 rows in, 6 rows out: ["r1", "r2", "r3", "r4", "r5", "r6"]
Show the solution

One sentence: the loop only writes a batch when it is full, so the last, partial batch is still sitting in the Vec when the loop ends.

The fix: flush the remainder after the loop. And a test whose row count is not a multiple of the batch size, which is why csv2json’s tests run with a batch of 2 on 5 rows.

src/main.rs
const BATCH: usize = 3;

fn main() {
    let rows = ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"];
    let mut written: Vec<&str> = Vec::new();

    let mut batch: Vec<&str> = Vec::with_capacity(BATCH);
    for row in rows {
        batch.push(row);
        if batch.len() == BATCH {
            written.extend(&batch);
            batch.clear();
        }
    }
    written.extend(&batch); // the last, smaller batch

    println!(
        "{} rows in, {} rows out: {written:?}",
        rows.len(),
        written.len()
    );
}
$ cargo run
8 rows in, 8 rows out: ["r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8"]

written.extend(&batch) with an empty batch adds nothing, so the line is safe even when the count happens to be a multiple of the batch size.

The csv2json exit check

Your csv2json passes when every line here is true:

CheckHow to verify
Memory stays flat on 1M rows/usr/bin/time -l (macOS) or -v (Linux): peak memory about the same for 100K and 1M rows
A bad row never stops the runAdd a row with a word for a score, one with missing fields, one with a broken byte (printf '\xff' into the file): all three appear in the errors file, the run finishes
Every rejected row has the line it starts onOpen the CSV at that line; check a row after a multi-line comment
The batch size changes nothing--batch 1 and --batch 10000 give identical files (cmp)
Arabic text survivesA comment with ، keeps its words apart
cargo test, cargo clippy --all-targets, cargo fmt --checkAll silent except the test report
README with the benchmarkYour numbers, your machine, and how to reproduce them

What PHP would have done

ProblemPHPRust
1. Stopping at the first errorSame choice: exceptions stop, a loop reports allSame choice, made visible by the return type
2. Reading a counter a closure changesuse (&$count): works, no checkCompile error E0502
3. Writing to one array from many workersSeparate processes cannot share the array at allCompile error E0596; collect instead
4. A missing optional field$data['comment']: a warning and nullRejected until the type says Option
5. The forgotten last batchThe same bug with array_chunk by handThe same bug: only a test with an odd count finds it

Remember

  • The bugs that compile are the ones tests must cover: early returns, partial batches, optional fields.

Week 4 leaves the command line: async Rust with tokio, HTTP calls, a database, and a Rust worker that a Laravel artisan command runs.