Course › Week 1 · Basics and ownership › Day 7 · lesson 7 of 42 · 20 min reading + 1–2 h practice
Week 1 checkpoint
Five broken programs to fix and explain. Pass them all before Week 2.
On this page
Five programs that do not compile, one for each idea of this week. For each: read the error, say in one sentence what Rust is protecting you from, then fix it without .clone() and without .unwrap(). Write your sentence down before you open the answer.
If any of them takes you more than 15 minutes, re-read that day’s lesson before you start Week 2. Everything next week assumes these five.
1. A booking passed to a function
struct Booking {
guest: String,
nights: u32,
}
fn print_booking(booking: Booking) {
println!("{}: {} nights", booking.guest, booking.nights);
}
fn main() {
let booking = Booking {
guest: String::from("Lina"),
nights: 3,
};
print_booking(booking);
println!("Send the invoice to {}", booking.guest);
}
error[E0382]: borrow of moved value: `booking`
--> src/main.rs:17:40
|
11 | let booking = Booking {
| ------- move occurs because `booking` has type `Booking`, which does not implement the `Copy` trait
...
16 | print_booking(booking);
| ------- value moved here
17 | println!("Send the invoice to {}", booking.guest);
| ^^^^^^^^^^^^^ value borrowed here after move
|
note: consider changing this parameter type in function `print_booking` to borrow instead if owning the value isn't necessary
--> src/main.rs:6:27
|
6 | fn print_booking(booking: Booking) {
| ------------- ^^^^^^^ this parameter takes ownership of the value
| |
| in this function
note: if `Booking` implemented `Clone`, you could clone the value
--> src/main.rs:1:1
|
1 | struct Booking {
| ^^^^^^^^^^^^^^ consider implementing `Clone` for this type
...
16 | print_booking(booking);
| ------- you could clone this value
For more information about this error, try `rustc --explain E0382`.
error: could not compile `hello` (bin "hello") due to 1 previous errorShow the solution
One sentence: print_booking took ownership of the booking and freed it when it returned, so main was using a value that no longer existed.
The fix: the function only reads the booking, so it borrows it (Day 4).
struct Booking {
guest: String,
nights: u32,
}
fn print_booking(booking: &Booking) {
println!("{}: {} nights", booking.guest, booking.nights);
}
fn main() {
let booking = Booking {
guest: String::from("Lina"),
nights: 3,
};
print_booking(&booking);
println!("Send the invoice to {}", booking.guest);
}
Lina: 3 nights
Send the invoice to Lina2. Changing a name someone is still reading
fn add_title(name: &mut String) {
name.insert_str(0, "Ms ");
}
fn main() {
let mut guest = String::from("Lina");
let greeting = &guest;
add_title(&mut guest);
println!("Hello, {greeting}");
}
error[E0502]: cannot borrow `guest` as mutable because it is also borrowed as immutable
--> src/main.rs:9:15
|
8 | let greeting = &guest;
| ------ immutable borrow occurs here
9 | add_title(&mut guest);
| ^^^^^^^^^^ mutable borrow occurs here
10 |
11 | println!("Hello, {greeting}");
| -------- 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: greeting was still going to read guest while add_title changed it, and Rust never lets a value be changed while a reader exists.
The fix: decide what you meant. To greet with the title, change first and read after. The borrow then starts after the change.
fn add_title(name: &mut String) {
name.insert_str(0, "Ms ");
}
fn main() {
let mut guest = String::from("Lina");
add_title(&mut guest);
let greeting = &guest;
println!("Hello, {greeting}");
}
Hello, Ms Lina3. A status nobody handled
enum Status {
Pending,
Confirmed,
Cancelled,
CheckedOut,
}
fn can_review(status: &Status) -> bool {
match status {
Status::Pending => false,
Status::Confirmed => false,
Status::Cancelled => false,
}
}
fn main() {
let statuses = [
Status::Pending,
Status::Confirmed,
Status::Cancelled,
Status::CheckedOut,
];
for status in &statuses {
println!("{}", can_review(status));
}
}
error[E0004]: non-exhaustive patterns: `&Status::CheckedOut` not covered
--> src/main.rs:9:11
|
9 | match status {
| ^^^^^^ pattern `&Status::CheckedOut` not covered
|
note: `Status` defined here
--> src/main.rs:1:6
|
1 | enum Status {
| ^^^^^^
...
5 | CheckedOut,
| ---------- not covered
= note: the matched value is of type `&Status`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
12 ~ Status::Cancelled => false,
13 ~ &Status::CheckedOut => todo!(),
|
For more information about this error, try `rustc --explain E0004`.
error: could not compile `hello` (bin "hello") due to 1 previous errorShow the solution
One sentence: a booking can be checked out, and the function never said what happens then, so Rust refuses to guess.
The fix: handle the missing case. Grouping the false cases with | keeps the one that matters visible. A _ => false would also compile, and would silently answer false for any status added later: exactly the bug match protects you from.
enum Status {
Pending,
Confirmed,
Cancelled,
CheckedOut,
}
fn can_review(status: &Status) -> bool {
match status {
Status::Pending | Status::Confirmed | Status::Cancelled => false,
Status::CheckedOut => true,
}
}
fn main() {
let statuses = [
Status::Pending,
Status::Confirmed,
Status::Cancelled,
Status::CheckedOut,
];
for status in &statuses {
println!("{}", can_review(status));
}
}
false
false
false
true4. A position that may not exist
fn message_of(line: &str) -> &str {
let colon: usize = line.find(": ");
&line[colon + 2..]
}
fn main() {
println!(
"{}",
message_of("[2026-11-30 09:41:03] production.ERROR: Deadlock")
);
println!("{}", message_of("#0 {main}"));
}
error[E0308]: mismatched types
--> src/main.rs:2:24
|
2 | let colon: usize = line.find(": ");
| ----- ^^^^^^^^^^^^^^^ expected `usize`, found `Option<usize>`
| |
| expected due to this
|
= note: expected type `usize`
found enum `Option<usize>`
help: consider using `Option::expect` to unwrap the `Option<usize>` value, panicking if the value is an `Option::None`
|
2 | let colon: usize = line.find(": ").expect("REASON");
| +++++++++++++++++
For more information about this error, try `rustc --explain E0308`.
error: could not compile `hello` (bin "hello") due to 1 previous errorShow the solution
One sentence: find returns None when the text is not there, as on the stack-trace line, and the code treated a maybe-position as a real one.
The fix: the function must be able to say “no message”, so it returns Option<&str>, and ? passes the None on (Day 5).
fn message_of(line: &str) -> Option<&str> {
let colon = line.find(": ")?;
Some(&line[colon + 2..])
}
fn main() {
let lines = [
"[2026-11-30 09:41:03] production.ERROR: Deadlock",
"#0 {main}",
];
for line in lines {
match message_of(line) {
Some(message) => println!("message: {message}"),
None => println!("no message: {line}"),
}
}
}
message: Deadlock
no message: #0 {main}5. Adding a night through a reference
struct Booking {
guest: String,
nights: u32,
}
fn extend(booking: &Booking) {
booking.nights += 1;
}
fn main() {
let booking = Booking {
guest: String::from("Omar"),
nights: 2,
};
extend(&booking);
println!("{} now stays {} nights", booking.guest, booking.nights);
}
error[E0594]: cannot assign to `booking.nights`, which is behind a `&` reference
--> src/main.rs:7:5
|
7 | booking.nights += 1;
| ^^^^^^^^^^^^^^^^^^^ `booking` is a `&` reference, so it cannot be written to
|
help: consider changing this to be a mutable reference
|
6 | fn extend(booking: &mut Booking) {
| +++
For more information about this error, try `rustc --explain E0594`.
error: could not compile `hello` (bin "hello") due to 1 previous errorShow the solution
One sentence: a & reference only allows reading, and changing the booking must be visible at every step: the variable, the call and the parameter.
The fix: three changes, all of them needed: let mut booking, extend(&mut booking), and booking: &mut Booking (Day 4). The compiler only pointed at the last one; fix it and it points at the next.
struct Booking {
guest: String,
nights: u32,
}
fn extend(booking: &mut Booking) {
booking.nights += 1;
}
fn main() {
let mut booking = Booking {
guest: String::from("Omar"),
nights: 2,
};
extend(&mut booking);
println!("{} now stays {} nights", booking.guest, booking.nights);
}
Omar now stays 3 nightsThe logstat exit check
Your logstat from Day 6 passes when every line here is true:
| Check | How to verify |
|---|---|
| Counts a real Laravel log correctly | Pick one level and compare with grep -c "production.ERROR:" laravel.log (adjust the environment name). The numbers must match. |
| Stack-trace lines are never counted as entries | The “other lines” number is not zero on a log with exceptions. |
| No path: usage message, exit code 2 | cargo run; echo $? |
| Missing file: clear message, exit code 1 | cargo run -- nope.log; echo $? |
No .clone() added to silence the compiler | Search the file. Each one left needs a reason you can say. |
No .unwrap() | Search the file. |
cargo clippy and cargo fmt --check are silent | Run both. |
| On GitHub, with a README | One paragraph and one usage line is enough. |
What PHP would have done
The same five mistakes in PHP compile, run, and fail later, or never fail at all:
| Mistake | PHP | Rust |
|---|---|---|
| 1. Using a value after giving it away | No such idea: objects are shared, so it “works” | Compile error E0382 |
| 2. Changing a value someone is reading | Works, and the reader silently sees the new value | Compile error E0502 |
| 3. A forgotten case | UnhandledMatchError when the case first happens in production | Compile error E0004 |
| 4. Using a maybe-value as a value | strpos() returns false, used as 0: wrong substring, no error | Compile error E0308 |
| 5. Changing through a read-only handle | No read-only handles: any function can change an object you pass it | Compile error E0594 |
Remember
- Fix the design the error points at, not the error: no
.clone()or.unwrap()to make it go away.
Week 2 starts by splitting logstat into modules, then gives it real flags, a proper error type and tests.