Then, we add the following dependencies to the Cargo.toml file:
Here’s what each dependency does:
chrono is used to get the current date and time.
colorize is used to color the output.
rand is used to generate random IDs.
serde and serde_json are used to get the data from the JSON file.
Creating the folder structure
Our src folder will look like this:
Now, in the main.rs file, I’ll import all modules:
Creating the structs
Before we start, let’s create the structs that we’ll use to store the data. In the structs/mod.rs file, we’ll create the following structs:
Creating the utility functions
In the utils/mod.rs file, we’ll import the dependencies and create the utility functions:
The first function is to create the global data file if it doesn’t exist:
The next function is to read the arguments from the command line. Before creating a function, we define a struct called Command in the structs module:
Now, we can create the get_args function.
The next function returns a timestamp.
After that, we create a function to generate a random ID:
The next function is to read the data from the JSON file:
The last function is to write the data to the JSON file:
And, that’s it for the utility functions.
Creating the todo functions
Now, we create the functions that will be used to add, remove, and list todos. In the todo/mod.rs file, import the dependencies.
The first function is to add a todo:
The next function is to list todos:
We then create a function to mark a todo as done:
The next function is to remove a todo:
Now, we have all the functions we need to create a todo app. We should integrate and make it work.
Integrating the functions
In the app/mod.rs file, import the dependencies.
We export a start function that will be called in the main.rs file.
We first check and create the data file if it doesn’t exist:
We then get the command and arguments:
We then match the command and call the appropriate function:
As for the help, we do this.
Now, in the main.rs file, add this function call:
Now, we can run the app using cargo run. You should see something like this:
Conclusion
Thanks for reading. I hope you enjoyed this tutorial. If you have any questions, feel free to ask in the comments. You can also check out the source code here.