Building a CLI Task Manager in Rust: From Zero to Working App
Not a Medium member? Read it here
After learning the basic concepts, it’s important to put them into practice with a practical project. In this two part article, we’ll build a command line task manager which will cover concepts we have explored so far, including data types, Enums, structs, pattern matching, error handling, traits, generics, and ownership.
What We’ll Build
The task manager will allow users to:
- Add tasks with title, description, and priority
- List all tasks sorted by priority
- Update task status
- Delete tasks
The first thing that i do when i learn any language , framework , i always start with a project and the move on deeper and deeper . So the idea is to create this simple project to solidify our understanding of Rust fundamentals in a practical context.
Part 1: Setting Up the Core Components
But First, Set up you Rust Environment : Before diving in, ensure your Rust environment is properly configured. For instructions on setting up Rust, refer to this guide from our previous article.
Setting Up the Project
Let’s start by creating a new Rust project using Cargo, Rust’s package manager and build tool:
cargo new rust_task_manager
cd rust_task_manager
cargo new rust_task_manager
cd rust_task_manager
This creates a new directory with the following structure:
rust_task_manager/
├── Cargo.toml
└── src/
└── main.rs
rust_task_manager/
├── Cargo.toml
└── src/
└── main.rs
The Cargo.toml file is your project’s manifest, containing metadata and dependencies:
[package]
name = "rust_task_manager"
version = "0.1.0"
edition = "2021"
[dependencies]
// We wont need any external dependencies but you can add it here
[package]
name = "rust_task_manager"
version = "0.1.0"
edition = "2021"
[dependencies]
// We wont need any external dependencies but you can add it here
For this project, we won’t need any external dependencies as we’ll be using only the Rust standard library. You can customize the package information with your name and other details if you wish.
Now, let’s replace the contents of src/main.rs with our task manager code. We’ll split our explanation into two parts for clarity.
Error Handling
We’ll start by defining a custom error type that implements Rust’s Error trait, its always good to know what errors we can encounter so we can deal with it accordingly. Previously i would just jump in and ignore the testing and error handling part but it has cost me more and more debugging time. Thus have realized to start everything with error handling straight up.
To think about this part lest rethink our application, what do we want?
- Tasks: Would be stored in String
- Description: Stored as string but would need to store more text as its description
- Priority : a simple integer type would suffice.
Based on the above we can safely say that we can encounter the following :
- Invalid Input: When users provide empty or unsupported data.
- Task Not Found: When trying to update or delete a task that doesn’t exist.
- I/O Errors: Issues during file operations or other system interactions.
#[derive(Debug)]
enum TaskError {
InvalidInput(String), // For invalid or empty input
TaskNotFound(u32), // For operations on non-existent tasks
IoError(std::io::Error), // For I/O related issues
}
#[derive(Debug)]
enum TaskError {
InvalidInput(String), // For invalid or empty input
TaskNotFound(u32), // For operations on non-existent tasks
IoError(std::io::Error), // For I/O related issues
}
This Enum showcases:
- Enums with associated data: Each variant can hold specific data
- Error handling patterns: Creating domain specific errors
- Trait implementation: We implement
DisplayandErrorfor our custom type
Integrate the custom error type into Rust’s ecosystem by implementing the Display and Error traits. This lets our errors be used with other Rust libraries and error handling mechanisms.
fmt::Result {
match self {
TaskError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
TaskError::TaskNotFound(id) => write!(f, "Task with ID {} not found", id),
TaskError::IoError(err) => write!(f, "IO error: {}", err),
}
}
}
impl Error for TaskError {}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
impl fmt::Display for TaskError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TaskError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
TaskError::TaskNotFound(id) => write!(f, "Task with ID {} not found", id),
TaskError::IoError(err) => write!(f, "IO error: {}", err),
}
}
}
impl Error for TaskError {}
impl fmt::Display for TaskError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
TaskError::InvalidInput(msg) => write!(f, "Invalid input: {}", msg),
TaskError::TaskNotFound(id) => write!(f, "Task with ID {} not found", id),
TaskError::IoError(err) => write!(f, "IO error: {}", err),
}
}
}
impl Error for TaskError {}
impl fmt::Display for TaskError:
This block implements thefmt::Displaytrait for the EnumTaskErrortype. TheDisplaytrait is used to define how a type should be formatted as a user facing string, in our case for printing or logging.
We also implement
From<io::Error>for automatic conversion from I/O errors:
<button data-code="impl From for TaskError {
fn from(err: io::Error) -> Self {
TaskError::IoError(err)
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
impl From<io::Error> for TaskError {
fn from(err: io::Error) -> Self {
TaskError::IoError(err)
}
}
impl From<io::Error> for TaskError {
fn from(err: io::Error) -> Self {
TaskError::IoError(err)
}
}
Task Status and Priority
Next, we define enums for task status and priority
#[derive(Debug, Clone, PartialEq)]
enum Status {
Todo,
InProgress,
Done,
}
#[derive(Debug, Clone, PartialEq, Ord, PartialOrd, Eq)]
enum Priority {
Low,
Medium,
High,
}
#[derive(Debug, Clone, PartialEq)]
enum Status {
Todo,
InProgress,
Done,
}
#[derive(Debug, Clone, PartialEq, Ord, PartialOrd, Eq)]
enum Priority {
Low,
Medium,
High,
}
Converting from Strings
Both Enums implement FromStr trait to parse strings into our enum values
- This allows you to take user input (a string) and convert it into one of the defined
Statusvariants:
Result {
match s.to_lowercase().as_str() {
"todo" => Ok(Status::Todo),
"in_progress" | "inprogress" | "in-progress" => Ok(Status::InProgress),
"done" => Ok(Status::Done),
_ => Err(TaskError::InvalidInput(format!(
"Invalid status: {}. Use 'todo', 'in_progress', or 'done'",
s
))),
}
}
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
impl FromStr for Status {
type Err = TaskError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"todo" => Ok(Status::Todo),
"in_progress" | "inprogress" | "in-progress" => Ok(Status::InProgress),
"done" => Ok(Status::Done),
_ => Err(TaskError::InvalidInput(format!(
"Invalid status: {}. Use 'todo', 'in_progress', or 'done'",
s
))),
}
}
}
impl FromStr for Status {
type Err = TaskError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"todo" => Ok(Status::Todo),
"in_progress" | "inprogress" | "in-progress" => Ok(Status::InProgress),
"done" => Ok(Status::Done),
_ => Err(TaskError::InvalidInput(format!(
"Invalid status: {}. Use 'todo', 'in_progress', or 'done'",
s
))),
}
}
}
This demonstrates:
- Traits: Implementing standard traits
- Associated types: Using
type Errin the trait implementation - Result type: Returning
Resultwith custom error type - Pattern matching: Using pattern matching to handle different inputs
Task Struct
The Task struct stores our task information
<button data-code="#[derive(Debug, Clone)]
struct Task {
id: u32,
title: String,
description: Option,
status: Status,
priority: Priority,
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
#[derive(Debug, Clone)]
struct Task {
id: u32,
title: String,
description: Option<String>,
status: Status,
priority: Priority,
}
#[derive(Debug, Clone)]
struct Task {
id: u32,
title: String,
description: Option<String>,
status: Status,
priority: Priority,
}
This showcases:
- Structs: Defining a data structure
- Option type: Using
Option<String>for optional description - Custom types: Using our custom enums
We also implement methods for our struct:
<button data-code="impl Task {
fn new(id: u32, title: String, description: Option, status: Status, priority: Priority) -> Self {
Task {
id,
title,
description,
status,
priority,
}
}
fn display(&self) {
println!("Task {}: {}", self.id, self.title);
if let Some(desc) = &self.description {
println!(" Description: {}", desc);
}
println!(" Status: {}", self.status);
println!(" Priority: {}", self.priority);
}
}
Fields for Task” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
impl Task {
fn new(id: u32, title: String, description: Option<String>, status: Status, priority: Priority) -> Self {
Task {
id,
title,
description,
status,
priority,
}
}
fn display(&self) {
println!("Task {}: {}", self.id, self.title);
if let Some(desc) = &self.description {
println!(" Description: {}", desc);
}
println!(" Status: {}", self.status);
println!(" Priority: {}", self.priority);
}
}
Fields for Task
impl Task {
fn new(id: u32, title: String, description: Option<String>, status: Status, priority: Priority) -> Self {
Task {
id,
title,
description,
status,
priority,
}
}
fn display(&self) {
println!("Task {}: {}", self.id, self.title);
if let Some(desc) = &self.description {
println!(" Description: {}", desc);
}
println!(" Status: {}", self.status);
println!(" Priority: {}", self.priority);
}
}
Fields for Task
id: A unique identifier for the task.title: The name of the task.description: An optional field (Option<String>) that holds more details about the task.statusandpriority: Use the previously defined enums.
Associated Method
- Constructor Method:
Thenewmethod initializes a task: - Pattern matching with if let: Handling
Optionelegantly - Borrowing: Using references with
&self
Ownership:
Notice how title and description are taken by value, transferring ownership into the new Task.
Task Manager
The TaskManager struct manages our collection of tasks:
<button data-code="
// TaskManager struct to manage tasks
struct TaskManager {
tasks: HashMap,
next_id: u32,
}” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
// TaskManager struct to manage tasks
struct TaskManager {
tasks: HashMap<u32, Task>,
next_id: u32,
}
// TaskManager struct to manage tasks
struct TaskManager {
tasks: HashMap<u32, Task>,
next_id: u32,
}
This demonstrates:
- HashMap Usage: Tasks are stored in a
HashMapwhere each task is indexed by its uniqueid. - Tracking IDs: The
next_idfield helps ensure that each new task gets a unique identifier.
The implementation shows several important methods:
Self {
TaskManager {
tasks: HashMap::new(),
next_id: 1,
}
}
/*
Mutable Reference (&mut self):
Since you're modifying the state (adding a new task),
the method requires a mutable reference.
Ownership and Borrowing:
The title and description are moved into the new Task instance.
*/
fn add_task(&mut self, title: String, description: Option, priority: Priority) -> u32 {
let id = self.next_id;
let task = Task::new(id, title, description, Status::Todo, priority);
self.tasks.insert(id, task);
self.next_id += 1;
id
}
/*
Returns a reference to a task if found,
or an error if the task ID does not exist.
*/
fn get_task(&self, id: u32) -> Result {
self.tasks.get(&id).ok_or(TaskError::TaskNotFound(id))
}
/*
Uses get_mut to get a mutable reference to a
task so its status can be updated.
*/
fn update_status(&mut self, id: u32, status: Status) -> Result {
if let Some(task) = self.tasks.get_mut(&id) {
task.status = status;
Ok(())
} else {
Err(TaskError::TaskNotFound(id))
}
}
/*
Sorting:
The tasks are first sorted by their priority (from high to low)
and then by their IDs if two tasks share the same priority.
Iteration and Display:
Each task is then displayed using its display method.
*/
fn list_tasks(&self) {
if self.tasks.is_empty() {
println!("No tasks found.");
return;
}
// Convert HashMap to Vec for sorting
let mut tasks: Vec = self.tasks.values().collect();
// Sort by priority (High to Low) and then by ID
tasks.sort_by(|a, b| {
b.priority.cmp(&a.priority)
.then_with(|| a.id.cmp(&b.id))
});
for task in tasks {
task.display();
println!();
}
}
/*
The remove method of HashMap returns an Option—if the
task was found and removed, it returns Some, otherwise None.
*/
fn delete_task(&mut self, id: u32) -> Result {
if self.tasks.remove(&id).is_some() {
Ok(())
} else {
Err(TaskError::TaskNotFound(id))
}
}
}
” data-toggle-ms=”1200″ aria-label=”Copy code” data-nosnippet=”” class=”code-copy-btn absolute right-3 top-3 size-8 p-1.5 flex items-center justify-center bg-black/50 text-white rounded-md transition-colors duration-200 cursor-pointer hover:bg-black/70″>
impl TaskManager {
fn new() -> Self {
TaskManager {
tasks: HashMap::new(),
next_id: 1,
}
}
/*
Mutable Reference (&mut self):
Since you're modifying the state (adding a new task),
the method requires a mutable reference.
Ownership and Borrowing:
The title and description are moved into the new Task instance.
*/
fn add_task(&mut self, title: String, description: Option<String>, priority: Priority) -> u32 {
let id = self.next_id;
let task = Task::new(id, title, description, Status::Todo, priority);
self.tasks.insert(id, task);
self.next_id += 1;
id
}
/*
Returns a reference to a task if found,
or an error if the task ID does not exist.
*/
fn get_task(&self, id: u32) -> Result<&Task, TaskError> {
self.tasks.get(&id).ok_or(TaskError::TaskNotFound(id))
}
/*
Uses get_mut to get a mutable reference to a
task so its status can be updated.
*/
fn update_status(&mut self, id: u32, status: Status) -> Result<(), TaskError> {
if let Some(task) = self.tasks.get_mut(&id) {
task.status = status;
Ok(())
} else {
Err(TaskError::TaskNotFound(id))
}
}
/*
Sorting:
The tasks are first sorted by their priority (from high to low)
and then by their IDs if two tasks share the same priority.
Iteration and Display:
Each task is then displayed using its display method.
*/
fn list_tasks(&self) {
if self.tasks.is_empty() {
println!("No tasks found.");
return;
}
// Convert HashMap to Vec for sorting
let mut tasks: Vec<&Task> = self.tasks.values().collect();
// Sort by priority (High to Low) and then by ID
tasks.sort_by(|a, b| {
b.priority.cmp(&a.priority)
.then_with(|| a.id.cmp(&b.id))
});
for task in tasks {
task.display();
println!();
}
}
/*
The remove method of HashMap returns an Option—if the
task was found and removed, it returns Some, otherwise None.
*/
fn delete_task(&mut self, id: u32) -> Result<(), TaskError> {
if self.tasks.remove(&id).is_some() {
Ok(())
} else {
Err(TaskError::TaskNotFound(id))
}
}
}
impl TaskManager {
fn new() -> Self {
TaskManager {
tasks: HashMap::new(),
next_id: 1,
}
}
/*
Mutable Reference (&mut self):
Since you're modifying the state (adding a new task),
the method requires a mutable reference.
Ownership and Borrowing:
The title and description are moved into the new Task instance.
*/
fn add_task(&mut self, title: String, description: Option<String>, priority: Priority) -> u32 {
let id = self.next_id;
let task = Task::new(id, title, description, Status::Todo, priority);
self.tasks.insert(id, task);
self.next_id += 1;
id
}
/*
Returns a reference to a task if found,
or an error if the task ID does not exist.
*/
fn get_task(&self, id: u32) -> Result<&Task, TaskError> {
self.tasks.get(&id).ok_or(TaskError::TaskNotFound(id))
}
/*
Uses get_mut to get a mutable reference to a
task so its status can be updated.
*/
fn update_status(&mut self, id: u32, status: Status) -> Result<(), TaskError> {
if let Some(task) = self.tasks.get_mut(&id) {
task.status = status;
Ok(())
} else {
Err(TaskError::TaskNotFound(id))
}
}
/*
Sorting:
The tasks are first sorted by their priority (from high to low)
and then by their IDs if two tasks share the same priority.
Iteration and Display:
Each task is then displayed using its display method.
*/
fn list_tasks(&self) {
if self.tasks.is_empty() {
println!("No tasks found.");
return;
}
// Convert HashMap to Vec for sorting
let mut tasks: Vec<&Task> = self.tasks.values().collect();
// Sort by priority (High to Low) and then by ID
tasks.sort_by(|a, b| {
b.priority.cmp(&a.priority)
.then_with(|| a.id.cmp(&b.id))
});
for task in tasks {
task.display();
println!();
}
}
/*
The remove method of HashMap returns an Option—if the
task was found and removed, it returns Some, otherwise None.
*/
fn delete_task(&mut self, id: u32) -> Result<(), TaskError> {
if self.tasks.remove(&id).is_some() {
Ok(())
} else {
Err(TaskError::TaskNotFound(id))
}
}
}
These methods showcase:
- Mutable references: Using
&mut selffor methods that modify state - Ownership: Taking ownership of
titleanddescription - Borrowing: Returning references with
&Task - Result type: Returning
Resultfor operations that might fail
We will build the CLI interface in the next article, where will cover :
Very Important
Add this to the top of the project, otherwise it wont work
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use std::str::FromStr;
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::io::{self, Write};
use std::str::FromStr;
Wrapping Up Part 1
At this point, we’ve established a solid foundation for our task manager application. We’ve:
- Configured a new Rust project.
- Defined error handling strategy with a custom error type.
- Built key data structures (
TaskandTaskManager) along with supportive enums (StatusandPriority). - Implemented robust methods to add, retrieve, update, list, and delete tasks.
This setup not only covers fundamental Rust concepts like ownership, borrowing, and pattern matching but also instills best practices for error handling and testing early on. With these core components in place, our project is prepared for adding interactive features.
Stay tuned for Part 2, where we bring these elements together in a complete CLI interface!
Follow this series and join us in mastering Rust from scratch!
Reach out here on Linkedin


