Table of Contents
Introduction
In this tutorial, we will learn how to create a command-line Todo List application using the Go programming language. By the end of this tutorial, you will be able to build a simple application that allows users to manage their tasks efficiently.
Prerequisites
To follow along with this tutorial, you should have basic knowledge of the Go programming language. You should also have Go installed on your machine.
Setup
Before we begin, let’s make sure that Go is properly installed and set up on your system. Open a terminal or command prompt and type the following command to check if Go is installed:
go version
If Go is installed, you should see the version number. If not, please download and install Go from the official Go website.
Creating the Todo List Application
Let’s start creating the Todo List application step-by-step.
Step 1: Setting up the project structure
Create a new directory for your project and navigate to that directory in the terminal. We will use this directory to organize our code files.
mkdir todo-list-app
cd todo-list-app
Step 2: Initializing a Go module
In Go, modules are used to manage dependencies and versions. We need to initialize a Go module for our project. Run the following command to initialize a Go module:
go mod init github.com/your-username/todo-list-app
Replace your-username
with your GitHub username or any other preferred name.
Step 3: Creating the main package
Now, let’s create the main package file main.go
. Open your favorite text editor and create a new file named main.go
inside the todo-list-app
directory.
Add the following code to main.go
:
package main
func main() {
// TODO: Implement the application logic
}
Step 4: Defining the necessary data structures
In our Todo List application, we need to define the Task
structure to represent individual tasks. Add the following code at the top of main.go
:
type Task struct {
ID int
Title string
Done bool
}
Step 5: Implementing basic functionality
Let’s implement the basic functionality of our Todo List application. Replace the content of the main
function with the following code:
func main() {
tasks := make([]Task, 0)
// Print the menu
printMenu()
// Read user input
reader := bufio.NewReader(os.Stdin)
for {
fmt.Print("Enter option: ")
option, _ := reader.ReadString('\n')
option = strings.TrimSpace(option)
switch option {
case "1":
tasks = addTask(reader, tasks)
case "2":
tasks = toggleTask(reader, tasks)
case "3":
printTasks(tasks)
case "4":
os.Exit(0)
default:
fmt.Println("Invalid option. Please try again.")
}
}
}
In the above code, we initialize an empty slice tasks
to hold our tasks. We then print the menu options, read the user input, and implement the functionality based on the selected option.
Step 6: Implementing helper functions
Now, let’s implement the helper functions needed for our Todo List application.
6.1 printMenu function
Add the following code to the bottom of main.go
:
func printMenu() {
fmt.Println("========= TODO LIST APP =========")
fmt.Println("1. Add Task")
fmt.Println("2. Toggle Task Done")
fmt.Println("3. View Tasks")
fmt.Println("4. Exit")
fmt.Println("===============================")
}
The printMenu
function simply prints the available options for the user.
6.2 addTask function
Add the following code after the printMenu
function:
func addTask(reader *bufio.Reader, tasks []Task) []Task {
fmt.Print("Enter task title: ")
title, _ := reader.ReadString('\n')
title = strings.TrimSpace(title)
newTask := Task{
ID: len(tasks) + 1,
Title: title,
Done: false,
}
tasks = append(tasks, newTask)
fmt.Println("Task added successfully!")
return tasks
}
The addTask
function prompts the user to enter a task title, creates a new Task
object, assigns an ID and title to it, sets the Done
field to false
, appends it to the tasks
slice, and returns the updated tasks
slice.
6.3 toggleTask function
Add the following code after the addTask
function:
func toggleTask(reader *bufio.Reader, tasks []Task) []Task {
printTasks(tasks)
fmt.Print("Enter task ID to toggle: ")
id, _ := reader.ReadString('\n')
id = strings.TrimSpace(id)
for i := range tasks {
if strconv.Itoa(tasks[i].ID) == id {
tasks[i].Done = !tasks[i].Done
fmt.Println("Task toggled successfully!")
return tasks
}
}
fmt.Println("Task not found. Please try again.")
return tasks
}
The toggleTask
function first prints the list of tasks and then prompts the user to enter the ID of the task they want to toggle. It searches for the task based on the entered ID, toggles the Done
field, and returns the updated tasks
slice. If the task is not found, it displays an error message.
6.4 printTasks function
Add the following code after the toggleTask
function:
func printTasks(tasks []Task) {
if len(tasks) == 0 {
fmt.Println("No tasks found.")
return
}
for _, task := range tasks {
doneStatus := "Not Done"
if task.Done {
doneStatus = "Done"
}
fmt.Printf("%d. %s (%s)\n", task.ID, task.Title, doneStatus)
}
}
The printTasks
function prints the list of tasks with their IDs, titles, and status (done or not done). If no tasks are found, it displays a message saying “No tasks found.”
Step 7: Building and running the application
To build and run the Todo List application, go to your terminal and navigate to the todo-list-app
directory. Run the following command:
go build
This command will build the application and create an executable file named todo-list-app
in the same directory. Execute the following command to run the application:
./todo-list-app
You should now see the menu options and can start managing your tasks using the Todo List application.
Conclusion
Congratulations! You have successfully created a command-line Todo List application in Go. You learned the basics of Go programming, including creating data structures, implementing application logic, and utilizing input/output operations. Now you can expand upon this application by adding more features, such as deletion or persistence of tasks.
In this tutorial, we covered the Syntax and Basics and Functions and Packages categories, which are fundamental to getting started with Go development. Happy coding!