This program is a simple calendar app written in the Go programming language. It allows users to add events to specific dates and view those events when needed. This app is designed with simplicity in mind, making it an excellent starting point for anyone looking to learn more about programming in Go and how to interact with data in a basic calendar structure.
Objective
The main objective of this project is to create a simple calendar application where users can:
- Add events to specific dates
- View events for a given date
Code
package main import ( "fmt" "time" "strings" ) // Event represents an event with a title and a date type Event struct { Title string Date time.Time } // Calendar holds the events for the entire year type Calendar struct { Events map[string][]Event } // NewCalendar creates and returns a new empty Calendar func NewCalendar() *Calendar { return &Calendar{ Events: make(map[string][]Event), } } // AddEvent adds an event to the calendar func (c *Calendar) AddEvent(title string, date string) error { parsedDate, err := time.Parse("2006-01-02", date) if err != nil { return fmt.Errorf("invalid date format. Please use YYYY-MM-DD") } event := Event{Title: title, Date: parsedDate} dateKey := parsedDate.Format("2006-01-02") c.Events[dateKey] = append(c.Events[dateKey], event) return nil } // ViewEvents displays the events for a given date func (c *Calendar) ViewEvents(date string) { dateKey := date if events, found := c.Events[dateKey]; found { fmt.Printf("Events for %s:\n", dateKey) for _, event := range events { fmt.Printf("- %s\n", event.Title) } } else { fmt.Println("No events found for this date.") } } func main() { calendar := NewCalendar() // Add sample events calendar.AddEvent("Doctor's Appointment", "2025-01-17") calendar.AddEvent("Team Meeting", "2025-01-17") calendar.AddEvent("Yoga Session", "2025-01-18") // View events for today fmt.Println("Enter the date to view events (format: YYYY-MM-DD):") var date string fmt.Scanln(&date) // View events for the specified date calendar.ViewEvents(date) }
Program Structure
The program is divided into several parts:
- Event struct – Represents a single event with a title and a date.
- Calendar struct – Holds the events and provides methods for adding and viewing events.
- NewCalendar() – Initializes a new calendar with an empty map of events.
- AddEvent() – Allows the user to add an event to a specific date.
- ViewEvents() – Allows the user to view the events on a given date.
- main() – The main entry point of the program, where events are added, and user input is handled to view events.
How to Run the Program
- Ensure you have Go installed on your computer. You can download it from here.
- Save the Go code in a file named calendar.go.
- Open a terminal or command prompt and navigate to the directory where the file is saved.
- Run the command
go run calendar.go
to execute the program. - The program will prompt you to enter a date in the format YYYY-MM-DD to view the events.