Skip to content

Checkpoint: Protect a State Transition

The Course
•
24 min study
Exercise

Your turn

Define a Task with a Done field and a pointer method Finish that returns whether it actually changed the task. Call it twice on the same task, then print the two results and the final Done field.

Your working space Go
package main

func main() {
	// Build your solution here.
}
Hint 1: the idea

Check the current state before writing the new one.

Hint 2: a first step

Return false immediately when Done is already true.

Worked solution
Run the solution Go
package main

import (
	"fmt"
)

type Task struct{ Done bool }

func (t *Task) Finish() bool {
	if t.Done {
		return false
	}
	t.Done = true
	return true
}

func main() {
	task := Task{}
	fmt.Println(task.Finish())
	fmt.Println(task.Finish())
	fmt.Println(task.Done)
}
Text
true
false
true

The second call finds the task already done and returns false without writing. The queue's Finish uses the same check to reject a repeated done.

Was this article helpful?

Your response is saved on this device.