Boss lesson · Unit 08
A task manager
One program from an empty file: model, commands, errors, a report and tests
What you practise
- One program from an empty file: a data model in structs and enums, commands, errors as
Result, iterator pipelines, tests, and a refactor the compiler guides. What to learn next
Try a question from this lesson
Pick one
You are building a task manager. A task is waiting, in progress or finished. What is the best way to store that state?
Correct answer
An enum with three variants
Why
A string can hold a typo, two bools can both be true, and a number can be 7. An enum can only ever be one of its variants, and every match on it must handle all three. Wrong states cannot even be written down.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Start from the data
A Task has an id, a title and a Status. The App owns every task in a vector and remembers the next free id, so that no id is used twice.
TaskErr lists everything that can go wrong: a title that is empty, or an id that no task has.
Nothing runs yet, but most of the design is decided here.
#[derive(Debug, PartialEq)]
enum Status { Todo, Doing, Done }
struct Task {
id: i32,
title: String,
status: Status,
}
struct App {
tasks: Vec<Task>,
next_id: i32,
}
#[derive(Debug, PartialEq)]
enum TaskErr { NoTitle, NotFound(i32) }Concept
A change that can fail
Hidden from here on: the model and add.
Finishing a task can fail, because the id may not exist. So finish returns a Result too. The loop borrows each task for writing. A hit changes the status and ends the function with Ok(()).
Falling out of the loop means no task had that id.
impl App {
fn finish(&mut self, id: i32)
-> Result<(), TaskErr> {
for t in &mut self.tasks {
if t.id == id {
t.status = Status::Done;
return Ok(());
}
}
Err(TaskErr::NotFound(id))
}
}Concept
Commands are data
A command says what the user wants. It is an enum, with the details inside each variant.
run is the one door into the app. It matches on the command and passes the work on. Every arm gives the same type, so the match is the function's result.
Hidden: start, which works like finish but sets Doing.
enum Cmd {
Add(String),
Start(i32),
Finish(i32),
}
fn run(app: &mut App, cmd: Cmd)
-> Result<(), TaskErr> {
match cmd {
Cmd::Add(name) => app.add(&name),
Cmd::Start(id) => app.start(id),
Cmd::Finish(id) => app.finish(id),
}
}9 more exercises in the app
- 2× fill the blanks
- 3× type the answer
- 3× multiple choice
- 1× true or false
Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.