Explain it simply
Explain it simply
Starting with this lesson, you will build a small Task Manager that runs in the terminal, over three lessons. Part 1 uses only the basic pieces: a struct, a slice, functions and loops. Part 2 adds methods and error handling, and Part 3 saves the list to a file with auto-save.
Picture a notebook where every page holds a number, a to-do item and a checkbox for "finished". In Go, one page is a Task struct and the whole notebook is a []Task slice. Decide that shape before writing features, and the next two parts simply build on top of it.
Problem → Why → Solution
The problem: the tasks you add disappear
Most people new to Go write something like this first. They call addTask twice and then ask listTasks to print the list. It compiles and it runs, yet the screen shows only "Task list is empty."
No error message appears, so people reread addTask again and again looking for a bug. addTask is actually fine. The real problem is that main never stores the slice the function returns.
func main() {
var tasks []Task
addTask(tasks, "Learn Go basics") // returned slice is thrown away
addTask(tasks, "Build task manager") // same here
listTasks(tasks) // prints "Task list is empty."
}Why do the tasks never reach tasks?
When you pass a slice to a function, Go copies the slice header: a pointer to the array, a length and a capacity. append grows only the copy inside the function, and may even allocate a brand-new array. The tasks variable in main still has length 0. The change sticks only when you assign the returned slice back: tasks = addTask(tasks, ...).
Core concept: the data model and the slice header
When you start an app, do not jump straight into commands and menus. First decide what data the app handles. For this Task Manager we think it through in three steps.
1. Describe one task with a struct
A task has an ID (int), a Title (string) and a Done flag (bool). The field names start with a capital letter so they are exported. Lowercase would still work inside package main, but the encoding/json package used in Part 3 can only see exported fields.
2. Keep all tasks in a slice
var tasks []Task is a nil slice. Its length is 0, a range loop over it simply does nothing, and append works on it. You do not need make() before using it.
3. Ask: does the length change, or only an element?
A slice value is a small header: a pointer to an array, a length and a capacity. When a function writes tasks[i].Done = true, its copy of the header points at the same array, so the caller sees the change. append changes the header itself (the length, and sometimes the pointer), so it returns a new header that the caller must store.
Two slice headers, one backing array
------------------------------------
main: tasks {ptr, len=3, cap=4} --+
+--> [T1][T2][T3][ ]
addTask: tasks {ptr, len=3, cap=4} --+
append {ptr, len=4, cap=4} --+ writes T4 into slot 4
main still sees len=3| Function | What it does to the slice | Must it return the slice? |
|---|---|---|
| addTask | Grows the length with append | Yes |
| completeTask | Writes tasks[i].Done in place | No |
| listTasks | Only reads | No |
Capacity explains why the bug in the problem section is so confusing. While the array still has spare room, append really does write the new task into the shared array, but main's header keeps its old length and never looks at that slot.
Once the array is full, append copies every element into a bigger array that only the function knows about. Either way main sees nothing new, so the rule stays simple: always store what append returns.
- Decide the Task struct first
- Keep the tasks in a []Task
- Length changes: return the slice
- Element changes: write by index
Whenever a function calls append, think straight away: this function must return the slice and the caller must store it.
General pattern
type Item struct {
ID int
Name string
}
func addItem(items []Item, name string) []Item {
return append(items, Item{ID: len(items) + 1, Name: name})
}
var items []Item
items = addItem(items, "first") // always store the resultA struct defines the shape of one element, the function that calls append returns the new slice, and the caller stores that result back into the same variable.
Part 1 code: add, complete and list tasks
The program first prints the empty list, then adds three tasks. It marks ID 2 as done and also tries ID 7, which does not exist. completeTask reports found or not found with a bool; in Part 2 that bool becomes an error that can also say why something failed.
package main
import "fmt"
type Task struct {
ID int
Title string
Done bool
}
func addTask(tasks []Task, title string) []Task {
newTask := Task{
ID: len(tasks) + 1,
Title: title,
}
return append(tasks, newTask)
}
func completeTask(tasks []Task, id int) bool {
for i := range tasks {
if tasks[i].ID == id {
tasks[i].Done = true
return true
}
}
return false
}
func listTasks(tasks []Task) {
if len(tasks) == 0 {
fmt.Println("Task list is empty.")
return
}
for _, t := range tasks {
status := "[ ]"
if t.Done {
status = "[x]"
}
fmt.Printf("%s %d. %s\n", status, t.ID, t.Title)
}
}
func main() {
var tasks []Task
listTasks(tasks)
tasks = addTask(tasks, "Learn Go basics")
tasks = addTask(tasks, "Build task manager")
tasks = addTask(tasks, "Write tests")
fmt.Println("complete #2:", completeTask(tasks, 2))
fmt.Println("complete #7:", completeTask(tasks, 7))
listTasks(tasks)
}Code breakdown
- Exported fields
Title stringA field that starts with a capital letter is visible to other packages. In Part 3, json.MarshalIndent can write only these fields to the file.
- ID from the length
ID: len(tasks) + 1,As long as tasks are only added and never removed, len+1 counts 1, 2, 3 correctly. Once Part 2 adds Remove, this would produce duplicate IDs, so it is replaced by a nextID counter.
- Return the grown slice
return append(tasks, newTask)append returns a new slice header with the larger length. addTask returns it directly, and main stores it with tasks = addTask(...).
- Write through the index
tasks[i].Done = trueWriting through the index changes the element in the array that main shares. The length does not change, so completeTask returns only a found/not-found bool, not the slice.
- Empty list guard
if len(tasks) == 0 {len of a nil slice is 0. Without this guard the program would print nothing at all, and the user could not tell whether anything happened.
Task list is empty.
complete #2: true
complete #7: false
[ ] 1. Learn Go basics
[x] 2. Build task manager
[ ] 3. Write testsWhere this project goes next
The Part 1 code has two weaknesses. First, the tasks slice is passed into every function and handed back; if one caller forgets the assignment, the update is lost. Second, IDs come from len(tasks)+1, so after deleting a task, the next new task can reuse an existing ID.
Part 2 moves the slice and an ID counter into a TaskManager struct with pointer-receiver methods, so callers no longer store the slice themselves. The Task struct stays exactly as it is, apart from the JSON tags added in Part 3.
In real projects
In real projects
Returning the new slice from a function that changes it is the standard shape in production Go too. Standard library functions such as slices.Insert and slices.Delete return the result slice, and callers write s = slices.Delete(s, i, i+1). Once the pattern in this lesson makes sense, those APIs feel natural.
Deciding the data model first also pays off in CLI tools, API servers and background workers alike. The same struct ends up in database tables, JSON responses and log lines, so choosing field names and types early saves rework later. In code review, people often read the structs first to understand the whole app, and they flag any append whose result is not stored back, or is stored into the wrong variable by accident.
Common mistakes
Common mistakes
Not storing addTask's result
Writing just addTask(tasks, "x") compiles, yet the task is lost, because Go lets you discard an ordinary function's return value. A bare append(tasks, t) statement, by contrast, is a compile error ("value is not used"). Always write tasks = addTask(tasks, "x").
Changing the range variable
In for _, t := range tasks { t.Done = true }, t is a copy of each element, so the tasks in the slice never change. That is why completeTask loops with for i := range tasks and writes tasks[i].Done = true.
Lowercase field names
With type Task struct { id int; title string }, everything works inside package main, but in Part 3 json.MarshalIndent skips unexported fields and the file ends up holding empty objects like [{}]. No error appears, which makes it hard to track down.
Mini challenge
Find, count and clean up tasks
Reuse the Task struct and addTask from Part 1 and write three more functions. Then remove the finished tasks, add one new task, and look closely at the new task's ID.
- findTask(tasks, id) returns (Task, bool) in the comma-ok style
- pendingCount(tasks) returns how many tasks are not done
- removeDone(tasks) returns a slice of the unfinished tasks, and the caller stores it
- After removeDone, add "Deploy" and print every ID and title
package main
import "fmt"
type Task struct {
ID int
Title string
Done bool
}
// TODO: copy addTask from the lesson.
// findTask returns the matching task and true, or Task{} and false.
func findTask(tasks []Task, id int) (Task, bool) {
// TODO: loop over tasks and compare IDs
}
func pendingCount(tasks []Task) int {
// TODO: count the tasks whose Done is false
}
// removeDone returns a new slice that holds only unfinished tasks.
func removeDone(tasks []Task) []Task {
// TODO: append every unfinished task to a new slice
}
func main() {
// TODO: add three tasks, then set tasks[1].Done = true
// TODO: findTask for ID 3 and ID 9, print pendingCount
// TODO: tasks = removeDone(tasks), add "Deploy", print IDs and titles
fmt.Println("start here")
}Expected: found: Write tests, task 9 not found and pending: 2, then 1. Learn Go basics, 3. Write tests and 3. Deploy. The two tasks with ID 3 are exactly why Part 2 switches to a nextID counter.
Show hint
In removeDone, create an empty slice with make([]Task, 0, len(tasks)) and append each task that is not Done. If you spot a repeated ID, think about addTask's len(tasks)+1.
Show solution
package main
import "fmt"
type Task struct {
ID int
Title string
Done bool
}
func addTask(tasks []Task, title string) []Task {
return append(tasks, Task{ID: len(tasks) + 1, Title: title})
}
func findTask(tasks []Task, id int) (Task, bool) {
for _, t := range tasks {
if t.ID == id {
return t, true
}
}
return Task{}, false
}
func pendingCount(tasks []Task) int {
count := 0
for _, t := range tasks {
if !t.Done {
count++
}
}
return count
}
func removeDone(tasks []Task) []Task {
kept := make([]Task, 0, len(tasks))
for _, t := range tasks {
if !t.Done {
kept = append(kept, t)
}
}
return kept
}
func main() {
var tasks []Task
tasks = addTask(tasks, "Learn Go basics")
tasks = addTask(tasks, "Build task manager")
tasks = addTask(tasks, "Write tests")
tasks[1].Done = true
if t, ok := findTask(tasks, 3); ok {
fmt.Println("found:", t.Title)
}
if _, ok := findTask(tasks, 9); !ok {
fmt.Println("task 9 not found")
}
fmt.Println("pending:", pendingCount(tasks))
tasks = removeDone(tasks)
tasks = addTask(tasks, "Deploy")
for _, t := range tasks {
fmt.Printf("%d. %s\n", t.ID, t.Title)
}
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- Decide the data model, such as the Task struct, before writing features
- A slice is a header (pointer, length, capacity) that reaches a function as a copy
- A function that calls append returns the slice, and the caller stores it with tasks = ...
- Change an element through tasks[i], never through the range variable
- IDs from len+1 only work while nothing is deleted; Part 2 fixes that
A Tour of Go — Go