Golang

 

Introduction

In today’s fast-paced world, managing tasks and staying on top of deadlines is crucial. A task reminder application can help individuals organize and prioritize their responsibilities. In this tutorial, we will create a simple task reminder app using the Go programming language.

The objective of this task reminder application is to provide an easy way to add, view, and delete tasks. The program will display tasks that need to be done and remind the user about pending items. This app will help users efficiently manage their tasks by providing timely reminders.

Code for Task Reminder Application

package main

import (
    "fmt"
    "time"
    "os"
    "encoding/json"
)

type Task struct {
    ID          int    `json:"id"`
    Description string `json:"description"`
    Time        string `json:"time"`
}

var tasks []Task
var taskID = 1

// Function to add a task to the list
func addTask(description string, taskTime string) {
    task := Task{
        ID:          taskID,
        Description: description,
        Time:        taskTime,
    }
    tasks = append(tasks, task)
    taskID++
}

// Function to list all tasks
func listTasks() {
    if len(tasks) == 0 {
        fmt.Println("No tasks available.")
        return
    }
    fmt.Println("Your Tasks:")
    for _, task := range tasks {
        fmt.Printf("Task ID: %d | Description: %s | Due at: %s\n", task.ID, task.Description, task.Time)
    }
}

// Function to delete a task by ID
func deleteTask(id int) {
    for i, task := range tasks {
        if task.ID == id {
            tasks = append(tasks[:i], tasks[i+1:]...)
            fmt.Printf("Task with ID %d has been deleted.\n", id)
            return
        }
    }
    fmt.Println("Task ID not found.")
}

// Function to save tasks to a file
func saveTasksToFile() {
    file, err := os.Create("tasks.json")
    if err != nil {
        fmt.Println("Error creating file:", err)
        return
    }
    defer file.Close()

    jsonData, err := json.Marshal(tasks)
    if err != nil {
        fmt.Println("Error marshalling data:", err)
        return
    }

    file.Write(jsonData)
    fmt.Println("Tasks have been saved successfully!")
}

// Function to load tasks from a file
func loadTasksFromFile() {
    file, err := os.Open("tasks.json")
    if err != nil {
        fmt.Println("No previous tasks found.")
        return
    }
    defer file.Close()

    decoder := json.NewDecoder(file)
    err = decoder.Decode(&tasks)
    if err != nil {
        fmt.Println("Error reading data from file:", err)
        return
    }

    fmt.Println("Tasks have been loaded successfully!")
}

// Main function to run the reminder application
func main() {
    // Load existing tasks from file on startup
    loadTasksFromFile()

    // Display initial menu
    for {
        var choice int
        fmt.Println("\nTask Reminder Menu:")
        fmt.Println("1. Add Task")
        fmt.Println("2. List Tasks")
        fmt.Println("3. Delete Task")
        fmt.Println("4. Save and Exit")
        fmt.Print("Enter your choice: ")
        fmt.Scanln(&choice)

        switch choice {
        case 1:
            var description, taskTime string
            fmt.Print("Enter task description: ")
            fmt.Scanln(&description)
            fmt.Print("Enter task time (YYYY-MM-DD HH:MM): ")
            fmt.Scanln(&taskTime)
            addTask(description, taskTime)
        case 2:
            listTasks()
        case 3:
            var id int
            fmt.Print("Enter task ID to delete: ")
            fmt.Scanln(&id)
            deleteTask(id)
        case 4:
            saveTasksToFile()
            fmt.Println("Exiting program...")
            return
        default:
            fmt.Println("Invalid choice, please try again.")
        }
    }
}

Explanation of Program Structure

The program consists of the following key components:

  • Task struct: Defines the structure for a task, with fields for the task ID, description, and time.
  • addTask function: Adds a new task to the tasks list.
  • listTasks function: Displays all the tasks currently in the list.
  • deleteTask function: Deletes a task from the list using the task ID.
  • saveTasksToFile function: Saves the list of tasks to a JSON file.
  • loadTasksFromFile function: Loads the tasks from the saved file when the program starts.
  • main function: Runs the menu and allows the user to interact with the application by adding, listing, or deleting tasks.

The application also uses JSON to store tasks, which makes it easy to save and load tasks across sessions. It reads the tasks from the “tasks.json” file when started and saves any new or modified tasks to the file when the user chooses to exit the program.

How to Run the Program

To run this program, you need to have Go installed on your system. If you don’t have Go installed, you can download it from https://golang.org/dl/.

Once Go is installed, follow these steps:

  1. Create a new directory for your project and navigate to it.
  2. Create a new file called main.go and paste the above code into the file.
  3. Open a terminal and navigate to the directory where main.go is located.
  4. Run the following command to execute the program: go run main.go

You will now be able to interact with the task reminder app through the command line.

© 2025 Learn Programming. All rights reserved.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)