Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 132 ยท Projects

Project: Command-Line To-Do Manager

Build a to-do manager in Rust step by step: structs and enums for the model, a command parser with FromStr, text persistence, an input loop and tests.

A to-do manager is a small program, and that is exactly why it is a good second project. It needs nearly everything you have learned so far, yet each piece is short: structs for the data, enums for commands and priorities, a Vec to hold the tasks, Result and custom errors for bad input, FromStr to turn text into commands, and a text format to save and load the list.

We will build it in four stages. Every stage is a complete program that you can run and change, and the last one reads commands from the Input box like a tiny shell. The design rule for the whole project is simple: keep the logic in plain functions and types that never print or read anything, and put all input and output in a thin loop at the bottom. That makes the logic easy to test, which we will do at the end.

Our editor runs a single main.rs with only the standard library, so the program reads commands from stdin and saves to a file that exists only for one run. In a real project you would put the types in src/lib.rs, read std::env::args() or use a crate such as clap for the command line, and keep the file between runs. The structure you learn here does not change.

Stage 1: the model

Start with the data. A task has an id, a title, a priority and a done flag. A priority has exactly three possible values, so it is an enum, not a string or a number. The list owns the tasks and hands out ids.

Rust Stage 1: tasks, priorities and the list

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Some choices here deserve a closer look.

  • #[derive(PartialOrd, Ord)] on Priority orders the variants by their position: Low < Normal < High. You get sorting by priority for free, without numbers.
  • complete returns a bool for now. That is a deliberate shortcut; in stage 3 it becomes a Result with a real error.
  • pending returns impl Iterator<Item = &Task> instead of a Vec. The caller can loop, count or collect without the list allocating anything. Edition 2024 captures the borrow of &self automatically, so no lifetime annotation is needed.
  • derive(Default) on TodoList would give next_id: 0, which is a trap. That is why we write new() by hand and start at 1. If you do not want the trap, remove the Default derive; we keep it here to show that a derived default is not always the right default.

Stage 2: from text to commands

A user types add Buy milk !high. The program must turn that line into a value it can match on. Define the commands as an enum, then implement FromStr so that line.parse::<Command>() works exactly like parsing a number. Parsing can fail in several ways, so it gets its own error enum with a readable Display.

The syntax we support:

TEXT
add <title> [!low|!normal|!high]
done <id>
remove <id>
list
clear
help
quit
Rust Stage 2: parsing commands with FromStr

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Notice what the parser does not do: it does not look at the task list. done 99 parses fine, because 99 is a valid number. Whether task 99 exists is a question for the next stage. Keeping "is this syntactically valid?" separate from "can this be done right now?" makes both parts simpler and lets you test them separately.

A few details worth studying:

  • split_once(char::is_whitespace) splits at the first whitespace character, passing a function as the pattern. For "list" there is none, so we fall back to the whole line.
  • The ? in last[1..].parse::<Priority>()? returns a ParseError directly, because Priority::from_str already uses the same error type. When the types differ you would add a From impl or use map_err, as parse_id does.
  • last[1..] slices off the !. That is safe because we just checked that last starts with !, which is one byte long. Slicing strings by byte index panics when the index is not on a character boundary, so you must be sure, as we are here.
  • The match guard Some((title, last)) if last.starts_with('!') means a title such as Fix the 100% bug keeps working: it has a last word, but it does not start with !.

Stage 3: executing commands and saving the list

Now connect the commands to the list. The function that executes a command takes &mut TodoList and returns a Result<String, TodoError>, the text to show the user. It does not print. We also teach the list to turn itself into text and back, which is how we save it.

The file format is deliberately boring: a header line and one line per task with four tab-separated fields.

TEXT
todo-v1
1	0	normal	Buy milk
2	1	high	Write the report

Tabs cannot appear in a title, because add replaces them with spaces. Load errors mention the line number, because "the file is broken" is a useless message. The program saves to a String first (to_text), and writing that string to disk is a one-line job with std::fs::write.

Rust Stage 3: errors, execute and the save format

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

The interesting spots:

  • let [id, done, priority, title] = fields[..] else { ... }; is a let-else with a slice pattern. It succeeds only when the vector has exactly four items, and it binds each one. splitn(4, '\t') guarantees the title keeps any further tabs, although add never writes them.
  • The closure bad builds a BadFile error with the current line number, so each failure site is a one-liner. It captures line_number by reference.
  • next_id is recomputed as max(id + 1), so ids never repeat after a reload even if you removed the last task before saving.
  • remove finds the position first and then removes by index. Searching for a reference and then mutating the vector in the same breath would fight the borrow checker.
  • fs::write and fs::read_to_string take any path. Here the file lives only for the duration of this run, but the same code persists a real list on your machine.

Stage 4: the complete program

Finally the loop. execute turns a Command into a message, run reads lines and drives everything, and the input comes from stdin. The function run takes any BufRead and any Write, so the same code works with the real terminal, with a file, or with a string in a test.

Rust Stage 4: the complete to-do manager

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Read the output from the top and match each line with the command that produced it. Three things are worth noticing.

  1. Errors never stop the loop. A bad command prints error: ... and the loop continues. Only I/O failures abort the program, through ? on line? and writeln!.
  2. The program stops at quit. The last line of the input, add never reached, is never processed, because break leaves the loop. Try deleting the quit line to see what happens at end of input: lines() returns None and the loop ends by itself.
  3. run is generic over its input and output. main passes the real terminal; a test passes a byte slice and a Vec<u8>.

Testing the logic

Because execute, parse and the list never touch the terminal, tests are trivial. In a real project you put them at the bottom of the file and run cargo test. The runner in this editor compiles a plain program, not a test harness, so the block below is read-only. It will not run here, but it is valid test code.

Rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_priority_suffix() {
        let command: Command = "add Write the report !high".parse().unwrap();
        assert_eq!(
            command,
            Command::Add { title: "Write the report".into(), priority: Priority::High }
        );
    }

    #[test]
    fn rejects_unknown_priority() {
        let error = "add Walk !urgent".parse::<Command>().unwrap_err();
        assert_eq!(error, ParseError::BadPriority("urgent".into()));
    }

    #[test]
    fn completing_twice_fails() {
        let mut list = TodoList::new();
        let id = list.add("Task", Priority::Normal);
        assert_eq!(list.complete(id), Ok(()));
        assert_eq!(list.complete(id), Err(TodoError::AlreadyDone(id)));
    }

    #[test]
    fn whole_session_output() {
        let input = b"add Milk\nlist\nquit\n";
        let mut output = Vec::new();
        run(&input[..], &mut output).unwrap();
        let text = String::from_utf8(output).unwrap();
        assert!(text.contains("added #1"));
    }
}

The last test shows the payoff of the generic run: &input[..] is a &[u8], which implements BufRead, and &mut Vec<u8> implements Write. You can run the whole program, prompts and all, in memory. You can try the same idea right now, since the editor can run the checks as ordinary code:

Rust Running a session in memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Pitfalls and design notes

  • Do not print inside the logic. The moment TodoList::add calls println!, you cannot test it quietly or reuse it in a GUI or a web server. Return values and let the outer layer decide.
  • Ids instead of indexes. If the user types done 2, they mean the task they saw labelled #2, not tasks[2]. After remove 1 the indexes shift, but the ids stay put.
  • Keep errors typed. A String error is easy to write and awkward to handle. An enum lets a caller match on NotFound and decide what to do. See custom error types and error design.
  • Do not clone to appease the borrow checker. render borrows the tasks (Vec<&Task>) to sort them, with no copies of titles.
  • Real persistence needs more care. Writing a file in place can leave half a file if the program crashes. Production code writes to a temporary file and renames it. For structured data, a serialization format is better than a hand-written one; see text formats.

Ideas to extend it

  1. Add a priority <id> <level> command. Where must the change go: the parser, execute, or both?
  2. Add due dates as a number of days, and sort overdue tasks first.
  3. Make done accept several ids: done 1 2 3. Decide whether one bad id should abort the whole command.
  4. Save on every change and load at start, using the stage 3 format.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the parser live in impl FromStr for Command instead of a free function?

    Implementing FromStr plugs the type into the standard parse method and the str::parse::<T> convention. Speed and the ability to return Result are unrelated.
  2. 2. What is the main benefit of run taking impl BufRead and impl Write instead of using stdin and stdout directly?

    A &[u8] is a BufRead and a &mut Vec<u8> is a Write, so a test can feed input and inspect output without a terminal.
  3. 3. done 99 is accepted by the parser but rejected later. Why is that the right design?

    Syntax checks and state checks are different jobs. Splitting them keeps the parser pure and easy to test, and the executor returns TodoError::NotFound.
  4. 4. What does #[derive(PartialOrd, Ord)] on enum Priority { Low, Normal, High } give you?

    Derived ordering on an enum compares variants by their position in the declaration, so High is the greatest.
  5. 5. Why does remove find the position first and then call self.tasks.remove(position)?

    position returns a plain number, so the borrow of the vector ends before remove needs &mut. Holding a reference into the vector while mutating it would not compile.

Summary

  • Model closed sets of values (priorities, commands, errors) as enums; model records as structs.
  • Implement FromStr to turn text into your own types, and give parsing its own error enum with Display.
  • Separate syntax (the parser), state rules (the list and TodoError) and I/O (the loop); only the loop prints or reads.
  • A hand-written line format needs a version header, field validation and error messages with line numbers.
  • Generic BufRead and Write parameters make a whole interactive program testable in memory.
  • #[cfg(test)] mod tests runs with cargo test; keep tests next to the code they check.

Next: Project: A grep Clone