Go Hard 1
š§ Code Challenge
package main
import (
"errors"
"fmt"
"strings"
)
type Task struct {
Title string
Description string
Done bool
}
type TaskList struct {
Tasks []Task
}
func (tl *TaskList) AddTask(title, description string) error {
if strings.TrimSpace(title) == "" {
return errors.New("task title cannot be empty")
}
task := Task{
Title: title,
Description: description,
Done: false,
}
tl.Tasks = append(tl.Tasks, task)
return nil
}
func (tl *TaskList) CompleteTask(index int) error {
if index < 0 || index >= len(tl.Tasks) {
return errors.New("invalid task index")
}
tl.Tasks[index].Done = true
return nil
}
func (tl *TaskList) PrintTasks() {
for i, task := range tl.Tasks {
status := "Pending"
if task.Done {
status = "Completed"
}
fmt.Printf("%d. [%s] %s - %s\n", i+1, status, task.Title, task.Description)
}
}
func main() {
myTasks := TaskList{}
_ = myTasks.AddTask("Write blog post", "About Go structs and methods")
_ = myTasks.AddTask("Fix bug #404", "Resolve panic in login flow")
_ = myTasks.CompleteTask(0)
myTasks.PrintTasks()
}
Explain what this function does. Speak clearly and use keywords.