Skip to content

Change the Original Record

The Course
•
25 min study

Go passes arguments by value. Passing a struct copies its fields, so a function that receives a Task works on its own copy, and nothing it changes reaches the caller. That is safe, but a queue needs functions that do change records: finish a task, rename it, move its due date. A pointer is the way to ask for that. Passing a pointer copies an address, so the function can change the record at that address.

The address operator & produces a pointer, and *Task is the type of a pointer to a Task. Go lets you select fields directly through a struct pointer, so t.Title works on a *Task without writing (*t).Title.

Predict and run

Which update reaches the original?

Predict, then run Go
package main

import (
	"fmt"
)

type Task struct{ Title string }

func copyEdit(t Task) { t.Title = "Copy" }
func edit(t *Task)    { t.Title = "Review" }

func main() {
	task := Task{Title: "Read"}
	copyEdit(task)
	fmt.Println(task.Title)
	edit(&task)
	fmt.Println(task.Title)
}
Check your prediction
Text
Read
Review

Swap the two calls and predict both lines.

Trace it step by step

  1. task := Task{Title: "Read"} creates one record in main.
  2. copyEdit(task) copies the whole record into the parameter t. Setting t.Title changes the copy, which disappears when the function returns. task still says Read.
  3. edit(&task) copies only the address of task into t. t.Title = "Review" follows that address to the record in main and changes it.

The types keep you honest. If you forget the & and write edit(task), the program doesn't run with the wrong behaviour. It doesn't compile:

Text
./main.go:11:7: cannot use task (variable of struct type Task) as *Task value in argument to edit

A pointer into a slice

& works on any variable you could assign to, including a slice element. &tasks[1] is the address of the record stored in the slice, so a function that receives it changes the slice itself, not a copy.

Change a record stored in a slice Go
package main

import (
	"fmt"
)

type Task struct {
	Title string
	Done  bool
}

func finish(t *Task) { t.Done = true }

func main() {
	tasks := []Task{{Title: "Read"}, {Title: "Draft"}}
	finish(&tasks[1])
	for _, t := range tasks {
		fmt.Println(t.Title, t.Done)
	}
}
Text
Read false
Draft true

A pointer can be nil

The zero value of a pointer type is nil, an address that points nowhere. Following it stops the program. var t *Task followed by fmt.Println(t.Title) compiles, then fails at run time:

Text
panic: runtime error: invalid memory address or nil pointer dereference

A function that receives a pointer from code it doesn't control can check if t == nil first. Inside this course, pointers come from & on a real variable, so they are never nil.

Practice

Exercise

Your turn

Each task now has a due day. Write postpone, which takes a *Task and a number of days and pushes the due day back by that many days, but leaves a finished task alone. The starter has two tasks in a slice. Postpone both by 3 days, then print them. The output should be:

Text
Read 4 false
Draft 2 true
Your working space Go
package main

import (
	"fmt"
)

type Task struct {
	Title string
	Due   int
	Done  bool
}

func main() {
	tasks := []Task{{Title: "Read", Due: 1}, {Title: "Draft", Due: 2, Done: true}}
	for _, t := range tasks {
		fmt.Println(t.Title, t.Due, t.Done)
	}
}
Hint 1: the idea

The change must reach the records stored in the slice, so postpone needs their addresses, and the loop that calls it has to go through the index.

Hint 2: a first step

Write postpone with only the change to Due, ignoring the rule for finished tasks, and call it for every task before the print loop. If both due days change, the pointer reaches the slice. Then add the rule.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

type Task struct {
	Title string
	Due   int
	Done  bool
}

func postpone(t *Task, days int) {
	if t.Done {
		return
	}
	t.Due += days
}

func main() {
	tasks := []Task{{Title: "Read", Due: 1}, {Title: "Draft", Due: 2, Done: true}}
	for i := range tasks {
		postpone(&tasks[i], 3)
	}
	for _, t := range tasks {
		fmt.Println(t.Title, t.Due, t.Done)
	}
}
Text
Read 4 false
Draft 2 true

for _, t := range tasks followed by postpone(&t, 3) would compile and change nothing in the slice, because t is a copy and &t is the copy's address. The index loop gives postpone the address of each stored record.

Was this article helpful?

Your response is saved on this device.