Course › Week 2 · Errors, collections, traits › Day 7 · lesson 14 of 42 · 20 min reading + 1–2 h practice
Week 2 checkpoint
clippy clean, zero unwrap outside tests, and every failure ends in a clear message.
On this page
Five problems, one per theme of the week: modules, errors, collections, tests and clippy. Two of them compile fine: one has a bug only a test finds, one works but would not pass review. As last week, write your one-sentence explanation before opening the answer.
Then the exit check for logstat v2. Pass both before Week 3.
1. A module main.rs cannot reach
src/parse.rs holds the function; src/lib.rs declares the module; src/main.rs uses it:
use logstat::parse;
fn main() {
let line = "[2026-11-30 09:41:03] production.ERROR: Deadlock found";
match parse::entry_level(line) {
Some(level) => println!("{level}"),
None => println!("not an entry"),
}
}
warning: function `entry_level` is never used
--> src/parse.rs:1:8
|
1 | pub fn entry_level(line: &str) -> Option<&str> {
| ^^^^^^^^^^^
|
= note: `#[warn(dead_code)]` (part of `#[warn(unused)]`) on by default
error[E0603]: module `parse` is private
--> src/main.rs:1:14
|
1 | use logstat::parse;
| ^^^^^ private module
|
note: the module `parse` is defined here
--> src/lib.rs:1:1
|
1 | mod parse;
| ^^^^^^^^^
For more information about this error, try `rustc --explain E0603`.
error: could not compile `logstat` (bin "logstat") due to 1 previous errorsrc/lib.rs contains one line, mod parse;, and src/parse.rs has pub fn entry_level. The warning above the error is the same problem from the other side: inside the library nothing uses entry_level, and outside nothing can.
Show the solution
One sentence: entry_level is public inside its module, but the module itself is private to the library, so nothing outside the library can name it.
The fix: pub mod parse; in src/lib.rs. Visibility is checked at every step of a path: logstat::parse::entry_level needs parse and entry_level both public.
pub mod parse;
Show the output
ERROR2. Two kinds of failure, one error type
A file of nights, one number per line. Reading can fail with an io::Error, parsing with a ParseIntError, and the function promises an ImportError:
use std::fs;
use std::io;
use std::num::ParseIntError;
use std::process::ExitCode;
use thiserror::Error;
#[derive(Debug, Error)]
enum ImportError {
#[error("cannot read the file: {0}")]
Read(io::Error),
#[error("a line is not a number of nights: {0}")]
Nights(ParseIntError),
}
fn total_nights(path: &str) -> Result<u32, ImportError> {
let text = fs::read_to_string(path)?;
let mut total: u32 = 0;
for line in text.lines() {
let nights: u32 = line.trim().parse()?;
total += nights;
}
Ok(total)
}
fn main() -> ExitCode {
match total_nights("nights.txt") {
Ok(total) => {
println!("{total} nights");
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("import: {error}");
ExitCode::FAILURE
}
}
}
error[E0277]: `?` couldn't convert the error to `ImportError`
--> src/main.rs:18:40
|
17 | fn total_nights(path: &str) -> Result<u32, ImportError> {
| ------------------------ expected `ImportError` because of this
18 | let text = fs::read_to_string(path)?;
| ------------------------^ the trait `From<std::io::Error>` is not implemented for `ImportError`
| |
| this can't be annotated with `?` because it has type `Result<_, std::io::Error>`
|
note: `ImportError` needs to implement `From<std::io::Error>`
--> src/main.rs:9:1
|
9 | enum ImportError {
| ^^^^^^^^^^^^^^^^
= note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
error[E0271]: type mismatch resolving `<u32 as FromStr>::Err == ImportError`
--> src/main.rs:21:39
|
21 | let nights: u32 = line.trim().parse()?;
| ^^^^^ expected `ImportError`, found `ParseIntError`
Some errors have detailed explanations: E0271, E0277.
For more information about an error, try `rustc --explain E0271`.
error: could not compile `hello` (bin "hello") due to 2 previous errorsTwo errors, one cause. The first is the ? after read_to_string. The second is the ? after parse, reported differently because the compiler tried to make parse produce an ImportError directly.
Show the solution
One sentence: ? can only pass an io::Error up as an ImportError if a conversion between them exists, and none was written.
The fix: #[from] on each field. thiserror then writes the From conversion the compiler’s note asked for (Day 3), and ? uses it automatically. No map_err needed.
use std::fs;
use std::io;
use std::num::ParseIntError;
use std::process::ExitCode;
use thiserror::Error;
#[derive(Debug, Error)]
enum ImportError {
#[error("cannot read the file: {0}")]
Read(#[from] io::Error),
#[error("a line is not a number of nights: {0}")]
Nights(#[from] ParseIntError),
}
fn total_nights(path: &str) -> Result<u32, ImportError> {
let text = fs::read_to_string(path)?;
let mut total: u32 = 0;
for line in text.lines() {
let nights: u32 = line.trim().parse()?;
total += nights;
}
Ok(total)
}
fn main() -> ExitCode {
match total_nights("nights.txt") {
Ok(total) => {
println!("{total} nights");
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("import: {error}");
ExitCode::FAILURE
}
}
}
12 nightsUse #[from] when the wrapped error says enough on its own. When the message needs context the original error lacks, like the file path or the line number in logstat’s LogError, use map_err and add it, as logstat does.
3. Reading a map while changing it
use std::collections::HashMap;
fn main() {
let mut rates: HashMap<String, u64> = HashMap::new();
rates.insert(String::from("Nyhavn flat"), 15_010);
let old_rate = rates.get("Nyhavn flat");
rates.insert(String::from("Nyhavn flat"), 16_500);
println!("old: {old_rate:?}");
}
error[E0502]: cannot borrow `rates` as mutable because it is also borrowed as immutable
--> src/main.rs:8:5
|
7 | let old_rate = rates.get("Nyhavn flat");
| ----- immutable borrow occurs here
8 | rates.insert(String::from("Nyhavn flat"), 16_500);
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
9 |
10 | println!("old: {old_rate:?}");
| -------- immutable 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: get lends a reference into the map, and insert may change or move that very value while the reference is still going to be printed.
The fix: you want the old number, not a view into the map: .copied() copies the u64 out (it is Copy), and the borrow ends on that line.
use std::collections::HashMap;
fn main() {
let mut rates: HashMap<String, u64> = HashMap::new();
rates.insert(String::from("Nyhavn flat"), 15_010);
let old_rate: Option<u64> = rates.get("Nyhavn flat").copied();
rates.insert(String::from("Nyhavn flat"), 16_500);
println!("old: {old_rate:?}, new: {:?}", rates.get("Nyhavn flat"));
}
old: Some(15010), new: Some(16500)insert also returns the value it replaced, as an Option. So let old_rate = rates.insert(…, 16_500); does both in one step.
4. A test finds the bug
This compiles, and the function looks right. The test says otherwise:
/// True if the entry's timestamp falls on or before the given day ("2026-11-30").
pub fn on_or_before(timestamp: &str, day: &str) -> bool {
timestamp <= day
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn includes_the_day_itself() {
assert!(on_or_before("2026-11-30 09:41:03", "2026-11-30"));
}
#[test]
fn excludes_the_next_day() {
assert!(!on_or_before("2026-12-01 00:00:00", "2026-11-30"));
}
}
running 2 tests
test tests::excludes_the_next_day ... ok
test tests::includes_the_day_itself ... FAILED
failures:
---- tests::includes_the_day_itself stdout ----
thread 'tests::includes_the_day_itself' (9777) panicked at src/lib.rs:12:9:
assertion failed: on_or_before("2026-11-30 09:41:03", "2026-11-30")
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::includes_the_day_itself
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sShow the solution
One sentence: compared as text, "2026-11-30 09:41:03" is longer than "2026-11-30" with the same start, so it sorts after it, and every entry of the last day was left out.
The fix: compare the date part only. get(..10) is the slice that returns None instead of panicking when there are fewer than 10 bytes or byte 10 falls inside a character.
/// True if the entry's timestamp falls on or before the given day ("2026-11-30").
pub fn on_or_before(timestamp: &str, day: &str) -> bool {
match timestamp.get(..10) {
Some(date) => date <= day,
None => false,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn includes_the_day_itself() {
assert!(on_or_before("2026-11-30 09:41:03", "2026-11-30"));
}
#[test]
fn excludes_the_next_day() {
assert!(!on_or_before("2026-12-01 00:00:00", "2026-11-30"));
}
}
running 2 tests
test tests::excludes_the_next_day ... ok
test tests::includes_the_day_itself ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sThe bug is invisible on most days of a log and wrong on exactly the day people check. That is what a test for the edge is for.
5. It works, and clippy says no
A loop that a PHP developer writes by reflex:
fn total(prices: &[u64]) -> u64 {
let mut sum: u64 = 0;
for i in 0..prices.len() {
sum += prices[i];
}
sum
}
fn main() {
println!("{}", total(&[15_010, 15_010, 18_000]));
}
src/main.rs:3:14: warning: the loop variable `i` is only used to index `prices`48020Show the solution
One sentence: looping over positions and indexing is longer, checks every [i] against the length, and hides that the loop only ever reads each price once.
The fix: loop over the items, as on Day 2. (In Week 3 this whole function becomes prices.iter().sum().)
fn total(prices: &[u64]) -> u64 {
let mut sum: u64 = 0;
for price in prices {
sum += price;
}
sum
}
fn main() {
println!("{}", total(&[15_010, 15_010, 18_000]));
}
48020The logstat v2 exit check
Your logstat v2 passes when every line here is true:
| Check | How to verify |
|---|---|
cargo test passes, with tests for the parser, the filters and the counting | Run it; break parse_entry on purpose and watch a test fail |
cargo clippy --all-targets and cargo fmt --check are silent | --all-targets includes the test code |
No unwrap() or expect() outside #[cfg(test)] | Search src/ |
Every failure prints one sentence starting with logstat: on stderr | Missing file, bad --since, unreadable line |
| Wrong usage exits 2, a failed run exits 1, success exits 0 | echo $? after each |
--help explains every flag | Run it |
main.rs has no parsing or counting logic | Read it: flags in, report out |
Pushed to GitHub with a README showing --help and one example | Open the repository page |
What PHP would have done
| Problem | PHP | Rust |
|---|---|---|
| 1. Using an internal part from outside | Classes are public by default; nothing stops it | Compile error E0603 |
| 2. Two error kinds through one function | Any exception passes through, typed or not | Compile error E0277 until a conversion exists |
| 3. Reading a value while changing its container | Works; you may see the old or the new value | Compile error E0502 |
| 4. A string comparison bug on the last day | Same bug, same silence | Same bug: only a test finds it |
| 5. Loop by index | Normal style | clippy flags it |
Row 4 is the honest one: no compiler catches a wrong condition. That is why logstat has tests, in Rust as in PHP.
Remember
- A compiler error means the code is wrong; a passing build does not mean it is right: tests and clippy cover the rest.
Week 3 starts with closures, then iterators: the style most Rust code is written in, and the one that makes csv2json fast.