rust todo example

Here is a simple example of a todo program in Rust that allows you to add, list, and mark items as done:

rust todo example 

use std::env;

struct TodoItem {
    name: String,
    done: bool,
}

impl TodoItem {
    fn new(name: &str) -> TodoItem {
        TodoItem {
            name: name.to_string(),
            done: false,
        }
    }
}

struct TodoList {
    list: Vec<TodoItem>,
}

impl TodoList {
    fn new() -> TodoList {
        TodoList { list: Vec::new() }
    }

    fn add_todo(&mut self, name: &str) {
        self.list.push(TodoItem::new(name));
    }

    fn mark_done(&mut self, index: usize) {
        if index < self.list.len() {
            self.list[index].done = true;
        }
    }

    fn print_list(&self) {
        for (index, todo) in self.list.iter().enumerate() {
            println!("{}: {} {}", index, todo.name, if todo.done { "[DONE]" } else { "" });
        }
    }
}

fn main() {
    let mut todo_list = TodoList::new();
    let args: Vec<String> = env::args().collect();

    if args.len() < 2 {
        println!("Usage: todo <command> [<args>]");
        return;
    }

    let command = &args[1];
    match command.as_ref() {
        "add" => {
            if args.len() < 3 {
                println!("Usage: todo add <name>");
                return;
            }
            let name = &args[2];
            todo_list.add_todo(name);
        }
        "done" => {
            if args.len() < 3 {
                println!("Usage: todo done <index>");
                return;
            }
            let index: usize = args[2].parse().unwrap();
            todo_list.mark_done(index);
        }
        "list" => todo_list.print_list(),
        _ => println!("Unknown command"),
    }
}

The TodoItem struct represents a single todo item, with a name and a flag indicating whether it is done. The TodoList struct maintains a list of TodoItems. The TodoList implementation has methods for adding a new todo, marking a todo as done, and printing the list.

The main function parses the command-line arguments and dispatches to the appropriate method based on the command given.

I hope this helps! Let me know if you have any questions.

 

Leave a Reply

Your email address will not be published. Required fields are marked *