Skip to content

Put Behavior on a Type

The Course
•
25 min study

The postpone function in the last lesson only makes sense for a Task, yet nothing ties it to the type: a reader has to find it among all the other functions in the file. A method attaches behaviour to a type, so a task's operations are listed with it and called with a dot, as in task.Finish().

A method declares a receiver between func and the method name. A value receiver, as in (t Task), gets a copy, which fits a read-only calculation on a small struct. A pointer receiver, as in (t *Task), gets the address, so the method can update the original. When you call a pointer method on a variable, Go takes its address for you: task.Finish() means (&task).Finish().

Predict and run

Which call changes the field?

Predict, then run Go
package main

import (
	"fmt"
)

type Task struct {
	Title string
	Done  bool
}

func (t Task) Label() string {
	if t.Done {
		return t.Title + ": done"
	}
	return t.Title + ": open"
}

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

func main() {
	task := Task{Title: "Read"}
	fmt.Println(task.Label())
	task.Finish()
	fmt.Println(task.Label())
}
Check your prediction
Text
Read: open
Read: done

Remove the * from Finish's receiver. Predict the second label.

A receiver is a parameter

A method is a function whose first parameter is written before its name. The receiver follows the same copy rules as any parameter you met in the last lesson, so choosing between Task and *Task is the same decision as choosing a parameter type. The one difference is that Go adds the & for you at the call. That convenience has a cost: forgetting the * on a receiver is not a compile error. The method simply changes a copy.

Find the bug

This tracker should report two finished tasks. It prints the wrong count and no error appears. Run it, then decide which line is wrong before you open the hint.

Find the bug Go
package main

import (
	"fmt"
)

type Tracker struct {
	finished int
}

func (t Tracker) Record(done bool) {
	if done {
		t.finished++
	}
}

func main() {
	var tracker Tracker
	for _, done := range []bool{true, false, true} {
		tracker.Record(done)
	}
	fmt.Println("Finished:", tracker.finished)
}
Text
Finished: 0
Check your fix

Record has a value receiver, so each call increments a copy of tracker that is thrown away when the method returns. Give it a pointer receiver:

Fixed Go
package main

import (
	"fmt"
)

type Tracker struct {
	finished int
}

func (t *Tracker) Record(done bool) {
	if done {
		t.finished++
	}
}

func main() {
	var tracker Tracker
	for _, done := range []bool{true, false, true} {
		tracker.Record(done)
	}
	fmt.Println("Finished:", tracker.finished)
}
Text
Finished: 2

A quick way to spot this bug: a value-receiver method that assigns to a field of its receiver is almost always a mistake.

Practice

Exercise

Your turn

Build a Timer that collects the minutes spent on a task. Give it a method Add(minutes int) that adds to the total and ignores anything below 1, and a method Summary() string that returns the total as hours and minutes. The starter has empty versions of both with value receivers: fill them in and choose each receiver. It adds 50, -5 and 45 minutes, so it prints this once your methods work:

Text
1h 35m
Your working space Go
package main

import (
	"fmt"
)

type Timer struct {
	minutes int
}

// Both receivers start as values. Decide whether each should stay that way.
func (t Timer) Add(minutes int) {}

func (t Timer) Summary() string { return "" }

func main() {
	var timer Timer
	timer.Add(50)
	timer.Add(-5)
	timer.Add(45)
	fmt.Println(timer.Summary())
}
Hint 1: the idea

Ask of each method: does it change the timer, or only read it? A method that changes it needs the original, and a method that only reads can work on a copy.

Hint 2: a first step

Write Summary first and have it return fmt.Sprintf("%dh %dm", ...) using / 60 and % 60. With the empty Add it prints 0h 0m. Then write Add, run it, and if it still prints 0h 0m, look at its receiver.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

type Timer struct {
	minutes int
}

func (t *Timer) Add(minutes int) {
	if minutes < 1 {
		return
	}
	t.minutes += minutes
}

func (t Timer) Summary() string {
	return fmt.Sprintf("%dh %dm", t.minutes/60, t.minutes%60)
}

func main() {
	var timer Timer
	timer.Add(50)
	timer.Add(-5)
	timer.Add(45)
	fmt.Println(timer.Summary())
}
Text
1h 35m

Add changes the total, so it needs a pointer receiver; with (t Timer) the program would print 0h 0m, the same bug as the tracker. Summary only reads, so a value receiver is enough. Many Go programmers would still give every method of a type that has a pointer method a pointer receiver, so the set stays consistent. Day 4 shows why that choice matters for interfaces.

Was this article helpful?

Your response is saved on this device.