Connecting the Pieces: How the Rust Task Manager Comes Together
Not a Medium member? Read it here
Building the CLI Interface
Welcome to Part 2! In this section, we will integrate our core components into a fully interactive command line interface. Here, we will learn how to:
- Implement the main function and application loop.
- Handle user input dynamically.
- Utilize our previously defined error handling to manage user commands robustly.
What to Cover in Part 2
In this part, we build upon the foundation laid in Part 1 by:
- Setting up a command loop that continuously accepts and processes user commands.
- Providing a basic user friendly experience by offering clear instructions and error messages.
- Demonstrating advanced Rust features such as dynamic dispatch with
Box<dyn Error>and seamless error propagation using the ? operator.
Below is the implementation of the main function and command loop:
Result<(), Box> {
let mut task_manager = TaskManager::new();
println!("Welcome to Rust Task Manager!");
loop {
println!("nAvailable commands:");
println!(" add – Add a new task");
println!(" list – List all tasks");
println!(" update – Update task status");
println!(" delete – Delete a task");
println!(" exit – Exit the application");
let command = read_input("nEnter command: ")?;
match command.as_str() {
"add" => {
let title = read_input("Enter task title: ")?;
if title.is_empty() {
println!("Error: Title cannot be empty");
continue;
}
let description = {
let desc = read_input("Enter task description (optional): ")?;
if desc.is_empty() { None } else { Some(desc) }
};
let priority = loop {
let priority_str = read_input("Enter priority (low/medium/high): ")?;
match Priority::from_str(&priority_str) {
Ok(p) => break p,
Err(e) => {
println!("Error: {}. Please try again.", e);
continue;
}
}
};
let id = task_manager.add_task(title, description, priority);
println!("Task added successfully with ID: {}", id);
}
"list" => {
println!("nTask List:");
task_manager.list_tasks();
}
"update" => {
let id_str = read_input("Enter task ID: ")?;
let id = match id_str.parse::() {
Ok(id) => id,
Err(_) => {
println!("Error: Invalid ID format");
continue;
}
};
// Verify task exists
if let Err(e) = task_manager.get_task(id) {
println!("Error: {}", e);
continue;
}
let status = loop {
let status_str = read_input("Enter new status (todo/in_progress/done): ")?;
match Status::from_str(&status_str) {
Ok(s) => break s,
Err(e) => {
println!("Error: {}. Please try again.", e);
continue;
}
}
};
match task_manager.update_status(id, status) {
Ok(_) => println!("Task status updated successfully"),
Err(e) => println!("Error: {}", e),
}
}
"delete" => {
let id_str = read_input("Enter task ID to delete: ")?;
let id = match id_str.parse::() {
Ok(id) => id,
Err(_) => {
println!("Error: Invalid ID format");
continue;
}
};
match task_manager.delete_task(id) {
Ok(_) => println!("Task deleted successfully"),
Err(e) => println!("Error: {}", e),
}
}
"exit" => {
println!("Thank you for using Rust Task Manager. Goodbye!");
break;
}
_ => {
println!("Unknown command: {}. Please try again.", command);
}
}
}
Ok(())
}” 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″>
// Task Manager in Rust - Part 2
// Main function and application loop
fn main() -> Result<(), Box<dyn Error>> {
let mut task_manager = TaskManager::new();
println!("Welcome to Rust Task Manager!");
loop {
println!("nAvailable commands:");
println!(" add - Add a new task");
println!(" list - List all tasks");
println!(" update - Update task status");
println!(" delete - Delete a task");
println!(" exit - Exit the application");
let command = read_input("nEnter command: ")?;
match command.as_str() {
"add" => {
let title = read_input("Enter task title: ")?;
if title.is_empty() {
println!("Error: Title cannot be empty");
continue;
}
let description = {
let desc = read_input("Enter task description (optional): ")?;
if desc.is_empty() { None } else { Some(desc) }
};
let priority = loop {
let priority_str = read_input("Enter priority (low/medium/high): ")?;
match Priority::from_str(&priority_str) {
Ok(p) => break p,
Err(e) => {
println!("Error: {}. Please try again.", e);
continue;
}
}
};
let id = task_manager.add_task(title, description, priority);
println!("Task added successfully with ID: {}", id);
}
"list" => {
println!("nTask List:");
task_manager.list_tasks();
}
"update" => {
let id_str = read_input("Enter task ID: ")?;
let id = match id_str.parse::<u32>() {
Ok(id) => id,
Err(_) => {
println!("Error: Invalid ID format");
continue;
}
};
// Verify task exists
if let Err(e) = task_manager.get_task(id) {
println!("Error: {}", e);
continue;
}
let status = loop {
let status_str = read_input("Enter new status (todo/in_progress/done): ")?;
match Status::from_str(&status_str) {
Ok(s) => break s,
Err(e) => {
println!("Error: {}. Please try again.", e);
continue;
}
}
};
match task_manager.update_status(id, status) {
Ok(_) => println!("Task status updated successfully"),
Err(e) => println!("Error: {}", e),
}
}
"delete" => {
let id_str = read_input("Enter task ID to delete: ")?;
let id = match id_str.parse::<u32>() {
Ok(id) => id,
Err(_) => {
println!("Error: Invalid ID format");
continue;
}
};
match task_manager.delete_task(id) {
Ok(_) => println!("Task deleted successfully"),
Err(e) => println!("Error: {}", e),
}
}
"exit" => {
println!("Thank you for using Rust Task Manager. Goodbye!");
break;
}
_ => {
println!("Unknown command: {}. Please try again.", command);
}
}
}
Ok(())
}
// Task Manager in Rust - Part 2
// Main function and application loop
fn main() -> Result<(), Box<dyn Error>> {
let mut task_manager = TaskManager::new();
println!("Welcome to Rust Task Manager!");
loop {
println!("nAvailable commands:");
println!(" add - Add a new task");
println!(" list - List all tasks");
println!(" update - Update task status");
println!(" delete - Delete a task");
println!(" exit - Exit the application");
let command = read_input("nEnter command: ")?;
match command.as_str() {
"add" => {
let title = read_input("Enter task title: ")?;
if title.is_empty() {
println!("Error: Title cannot be empty");
continue;
}
let description = {
let desc = read_input("Enter task description (optional): ")?;
if desc.is_empty() { None } else { Some(desc) }
};
let priority = loop {
let priority_str = read_input("Enter priority (low/medium/high): ")?;
match Priority::from_str(&priority_str) {
Ok(p) => break p,
Err(e) => {
println!("Error: {}. Please try again.", e);
continue;
}
}
};
let id = task_manager.add_task(title, description, priority);
println!("Task added successfully with ID: {}", id);
}
"list" => {
println!("nTask List:");
task_manager.list_tasks();
}
"update" => {
let id_str = read_input("Enter task ID: ")?;
let id = match id_str.parse::<u32>() {
Ok(id) => id,
Err(_) => {
println!("Error: Invalid ID format");
continue;
}
};
// Verify task exists
if let Err(e) = task_manager.get_task(id) {
println!("Error: {}", e);
continue;
}
let status = loop {
let status_str = read_input("Enter new status (todo/in_progress/done): ")?;
match Status::from_str(&status_str) {
Ok(s) => break s,
Err(e) => {
println!("Error: {}. Please try again.", e);
continue;
}
}
};
match task_manager.update_status(id, status) {
Ok(_) => println!("Task status updated successfully"),
Err(e) => println!("Error: {}", e),
}
}
"delete" => {
let id_str = read_input("Enter task ID to delete: ")?;
let id = match id_str.parse::<u32>() {
Ok(id) => id,
Err(_) => {
println!("Error: Invalid ID format");
continue;
}
};
match task_manager.delete_task(id) {
Ok(_) => println!("Task deleted successfully"),
Err(e) => println!("Error: {}", e),
}
}
"exit" => {
println!("Thank you for using Rust Task Manager. Goodbye!");
break;
}
_ => {
println!("Unknown command: {}. Please try again.", command);
}
}
}
Ok(())
}
This demonstrates:
- Main function with error handling: Using
Result<(), Box<dyn Error>> - Trait objects: Using
Box<dyn Error>for dynamic dispatch - Loop constructs: Using
loopfor indefinite execution - Pattern matching: Using
matchfor command dispatch
Input Handling
We also created a helper function to read user input and:
Result {
print!("{}", prompt);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_string())
}” 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″>
fn read_input(prompt: &str) -> Result<String, TaskError> {
print!("{}", prompt);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_string())
}
fn read_input(prompt: &str) -> Result<String, TaskError> {
print!("{}", prompt);
io::stdout().flush()?;
let mut input = String::new();
io::stdin().read_line(&mut input)?;
Ok(input.trim().to_string())
}
This showcases:
- Error propagation: Using the ? operator
- String operations: Using
trim()andto_string() - I/O operations: Working with standard input/output
Lets Run It
Live Demo : Here
Key Rust Concepts Demonstrated
Our task manager application covers all the topics you mentioned:
- Data Types:
- Primitive types:
u32,String - Collection types:
HashMap - Custom types:
Task,Status,Priority
2. Enums, Structs, and Pattern Matching:
- Defined custom enums with variants
- Created structs with fields
- Used pattern matching throughout the code
3. Traits and Generics:
- Implemented traits like
Display,Error,FromStr - Used generic types with
Result<T, E>andOption<T>
4. Error Handling:
- Created custom error types
- Used
Resulttype for fallible operations - Applied the ? operator for error propagation
5. Lifetimes, Borrowing, and Ownership:
- Used references (& and
&mut) appropriately - Managed ownership of values
- Returned references with proper lifetimes
Conclusion
This project demonstrates how Rust’s features work together in a real-world application. We’ve built a functional task manager that showcases what we have learned so far and Rust’s strength:
- Safety: The compiler prevents common errors related to memory and concurrency
- Expressiveness: Pattern matching and traits enable clean, readable code
- Performance: Zero-cost abstractions allow high-level code with low-level performance
The complete code is available in the two code sections of this article. You can use this as a starting point for more advanced Rust projects, such as adding persistence to save tasks to a file or database, or creating a web API using a framework like Actix or Rocket.
Happy coding and safe assembling!
Follow this series and join us in mastering Rust from scratch!
Reach out here on Linkedin

