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.
On this page
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:
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}"),
}
}
rejected: 'four': invalid digit found in stringShow 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.
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}");
}
}
scores: [5, 3, 2]
rejected: 'four': invalid digit found in string
rejected: '': cannot parse integer from empty stringReturning 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
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");
}
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 errorShow 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.
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");
}
2 rejected
line 5: score is not a number
line 9: missing fields3. Pushing results from every core
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:?}");
}
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 errorShow 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.
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:?}");
}
["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:
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}"),
}
}
}
#1001: 5 "Clear explanations"
rejected: missing field `comment` at line 1 column 35Show 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.
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}"),
}
}
}
#1001: 5 Some("Clear explanations")
#1002: 3 None5. Eight rows in, six rows out
The batching loop compiles, passes a test with 6 rows, and loses data on real files:
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()
);
}
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.
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()
);
}
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:
| Check | How 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 run | Add 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 on | Open 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 survives | A comment with ، keeps its words apart |
cargo test, cargo clippy --all-targets, cargo fmt --check | All silent except the test report |
| README with the benchmark | Your numbers, your machine, and how to reproduce them |
What PHP would have done
| Problem | PHP | Rust |
|---|---|---|
| 1. Stopping at the first error | Same choice: exceptions stop, a loop reports all | Same choice, made visible by the return type |
| 2. Reading a counter a closure changes | use (&$count): works, no check | Compile error E0502 |
| 3. Writing to one array from many workers | Separate processes cannot share the array at all | Compile error E0596; collect instead |
| 4. A missing optional field | $data['comment']: a warning and null | Rejected until the type says Option |
| 5. The forgotten last batch | The same bug with array_chunk by hand | The 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.