A slice finds a record by position; the task queue needs to find one by ID, as in "finish task 7". A map from IDs to records does that lookup directly. But a map of structs has a rule that catches everyone once: you can't change a field of a record while it sits in the map.
Look up a struct in a map with the comma-ok form, task, ok := tasks[id]. The result is a copy. Change the copy, then assign the updated record back to the key. A missing key should not create a record by accident.
Predict and run
What happens to the requested ID?
package main
import (
"fmt"
)
type Task struct {
Title string
Done bool
}
func main() {
tasks := map[int]Task{2: {Title: "Read"}}
task, ok := tasks[2]
if ok {
task.Done = true
tasks[2] = task
}
fmt.Println(tasks[2].Done)
}Check your prediction
trueRemove the write-back. Why does the printed field stay false?
Why you can't assign to the field directly
The obvious line, tasks[2].Done = true, doesn't compile:
./main.go:7:2: cannot assign to struct field tasks[2].Done in mapA map moves its values around in memory as it grows, so Go never lets you hold on to the location of a value inside one. Reading tasks[2] always gives you a copy. That leaves three steps, and each one matters: read the copy, change the copy, store the copy. The ok check in between makes sure you only store a record that was already there.
Find the bug
This program finishes every task whose title starts with Draft. It runs without an error and finishes nothing. Find the missing step before you open the hint.
package main
import (
"fmt"
"strings"
)
type Task struct {
Title string
Done bool
}
func main() {
tasks := map[int]Task{1: {Title: "Draft intro"}, 2: {Title: "Read"}, 3: {Title: "Draft outro"}}
for id, task := range tasks {
if strings.HasPrefix(task.Title, "Draft") {
task.Done = true
}
_ = id
}
fmt.Println(tasks[1].Done, tasks[2].Done, tasks[3].Done)
}false false falseCheck your fix
task is a copy of the map value, and nothing stores it back. Use the key to write the changed copy into the map:
package main
import (
"fmt"
"strings"
)
type Task struct {
Title string
Done bool
}
func main() {
tasks := map[int]Task{1: {Title: "Draft intro"}, 2: {Title: "Read"}, 3: {Title: "Draft outro"}}
for id, task := range tasks {
if strings.HasPrefix(task.Title, "Draft") {
task.Done = true
tasks[id] = task
}
}
fmt.Println(tasks[1].Done, tasks[2].Done, tasks[3].Done)
}true false trueThe _ = id line in the buggy version was a clue: the key was fetched and never used, so nothing could have written to the map. Changing an existing key while ranging over a map is safe in Go.
Practice
Your turn
The starter keeps a count of finished and open tasks per person in a map[string]Stats, and has a list of events. For each event, add 1 to that person's Done or Open count, creating the person's entry if it isn't there yet. Then print Ana's and Ben's stats. The output should be:
Ana {Done:2 Open:1}
Ben {Done:0 Open:1}package main
import (
"fmt"
)
type Stats struct {
Done int
Open int
}
type Event struct {
Person string
Done bool
}
func main() {
events := []Event{{"Ana", true}, {"Ben", false}, {"Ana", false}, {"Ana", true}}
stats := map[string]Stats{}
fmt.Println(len(events), len(stats))
}Hint 1: the idea
Read, change, store, for each event. A person who isn't in the map yet reads as the zero Stats, which is exactly the right starting point here, so this time you don't need the ok check.
Hint 2: a first step
Inside a loop over events, write s := stats[e.Person], add to s.Done or s.Open, and print stats after the loop. If every count is still missing, look for the line that stores s.
Worked solution
package main
import (
"fmt"
)
type Stats struct {
Done int
Open int
}
type Event struct {
Person string
Done bool
}
func main() {
events := []Event{{"Ana", true}, {"Ben", false}, {"Ana", false}, {"Ana", true}}
stats := map[string]Stats{}
for _, e := range events {
s := stats[e.Person]
if e.Done {
s.Done++
} else {
s.Open++
}
stats[e.Person] = s
}
fmt.Printf("Ana %+v\n", stats["Ana"])
fmt.Printf("Ben %+v\n", stats["Ben"])
}Ana {Done:2 Open:1}
Ben {Done:0 Open:1}Here creating an entry is the goal, so a missing key's zero value is used on purpose. In the queue it is the opposite: finishing an ID that doesn't exist must be an error, which is why the queue checks ok first. %+v prints field names, which makes a struct easy to read in output.
Completion is saved in this browser only. It does not measure mastery.