PEAKIQ - Software Solutions & Digital Innovation Peakiq Software Development

Peakiq Blog

Building a Simple CLI To-Do App in Rust

Step-by-step guide to building a Rust CLI To-Do application using Cargo. Learn CRUD operations, struct design, and command-line interaction in Rust.

Editorial2 min read389 words
Building a Simple CLI To-Do App in Rust

Getting Started

To follow along, ensure you have Rust installed on your system. You can install Rust using Rustup.

Once installed, create a new Rust project:

cargo new rust_todo
cd rust_todo

Now, open the main.rs file and start coding!

Writing the Code

Below is the full implementation of our simple CLI-based CRUD app in Rust:

use std::io::{stdin};

struct Task {
    id: u32,
    name: String,
}

fn main() {
    let mut tasks: Vec<Task> = Vec::new();
    loop {
        println!("\nSimple CRUD App");
        println!("1. Add Task");
        println!("2. View Tasks");
        println!("3. Delete Task");
        println!("4. Exit");
        println!("Enter your choice: ");

        let mut choice = String::new();
        stdin().read_line(&mut choice).unwrap();
        let choice: u32 = match choice.trim().parse() {
            Ok(num) => num,
            Err(_) => {
                println!("Invalid input. Please enter a number.");
                continue;
            }
        };

        match choice {
            1 => {
                println!("Enter task name: ");
                let mut name = String::new();
                stdin().read_line(&mut name).unwrap();
                let id = tasks.len() as u32 + 1;
                tasks.push(Task { id, name: name.trim().to_string() });
                println!("Task added successfully!");
            }
            2 => {
                println!("Tasks:");
                for task in &tasks {
                    println!("ID: {}, Name: {}", task.id, task.name);
                }
            }
            3 => {
                println!("Enter task ID to delete: ");
                let mut id = String::new();
                stdin().read_line(&mut id).unwrap();
                let id: u32 = match id.trim().parse() {
                    Ok(num) => num,
                    Err(_) => {
                        println!("Invalid ID. Please enter a valid number.");
                        continue;
                    }
                };
                tasks.retain(|task| task.id != id);
                println!("Task deleted successfully!");
            }
            4 => {
                println!("Exiting...");
                break;
            }
            _ => {
                println!("Invalid choice! Please try again.");
            }
        }
    }
}

Code Breakdown

1. Struct Definition

We define a Task struct that holds an id and a name.

2. Handling User Input

The stdin().read_line(&mut variable).unwrap(); reads input from the user.

3. Adding Tasks

New tasks are added to the tasks vector with an incremented ID.

4. Viewing Tasks

We loop through the tasks vector and print each task.

5. Deleting Tasks

We ask the user for an ID and filter out the task with that ID using retain.

6. Handling Invalid Input

We use match choice.trim().parse() to handle parsing errors gracefully.

Running the Program

To run the program, execute:

cargo run

Try adding, viewing, and deleting tasks to test its functionality!

Conclusion

This simple CRUD app demonstrates basic Rust concepts like structs, vectors, loops, and error handling. You can expand it by adding features such as persistent storage using files or a database.

Happy coding with Rust!