An order with three lines is one request, not three. If the second line cannot be reserved, the person who sent the order expects nothing to have happened: not two-thirds of an order, held in stock nobody asked for. A change that happens completely or not at all is called atomic. Getting it right is easy to forget, because the broken version works perfectly on every order that succeeds. It only goes wrong when a line fails partway through.
Predict and run
reserveNaive subtracts each line as it goes. The second line fails. What does the stock look like afterwards?
package main
import (
"fmt"
)
type Line struct {
Item string
Quantity int
}
func reserveNaive(stock map[string]int, lines []Line) error {
for _, line := range lines {
if line.Quantity > stock[line.Item] {
return fmt.Errorf("not enough %s", line.Item)
}
stock[line.Item] -= line.Quantity
}
return nil
}
func main() {
stock := map[string]int{"drill": 1, "tent": 5}
err := reserveNaive(stock, []Line{{"drill", 1}, {"tent", 6}})
fmt.Println(err)
fmt.Println(stock)
}Check your prediction
not enough tent
map[drill:0 tent:5]The order was rejected, yet the drill is gone. Nothing will ever give it back, because no order holds it. Put the tent line first and run again: the bug disappears, which shows how easy it is to miss in testing.
Work on a copy
The fix is to stage the changes on a copy and replace the real state only when every line has succeeded. maps.Clone makes the copy. If a line fails, the function returns, and the copy is simply dropped. The real map is never seen in a half-changed state, not even for a moment.
package main
import (
"fmt"
"maps"
)
type Line struct {
Item string
Quantity int
}
type Ledger struct {
stock map[string]int
}
func (l *Ledger) Reserve(lines []Line) error {
staged := maps.Clone(l.stock)
for _, line := range lines {
have := staged[line.Item]
if line.Quantity > have {
return fmt.Errorf("not enough %s: have %d, need %d", line.Item, have, line.Quantity)
}
staged[line.Item] = have - line.Quantity
}
l.stock = staged
return nil
}
func main() {
l := &Ledger{stock: map[string]int{"drill": 1, "tent": 5}}
fmt.Println(l.Reserve([]Line{{"drill", 1}, {"tent", 6}}), l.stock)
fmt.Println(l.Reserve([]Line{{"drill", 1}, {"tent", 5}}), l.stock)
}not enough tent: have 5, need 6 map[drill:1 tent:5]
<nil> map[drill:0 tent:0]The commit is one assignment, l.stock = staged, after the last check. Everything before it can fail freely. This is the shape of the project's Order and Cancel methods, and of the "commit a partial order" mutation the checks catch: replace maps.Clone(l.stock) with l.stock, and the copy is gone.
Why not check first, then apply?
Another common design validates every line in one pass and applies them all in a second pass. It avoids the copy, but each check looks at the stock before any line is applied. An order that lists the same item twice, tent:3 tent:3 against 5 tents, passes both checks and then takes 6. Staging does not have this problem, because the second tent line sees the stock the first line left. The project also rejects duplicate items in the parser, so every order has one line per item, but the ledger does not rely on that.
Copying a map costs time in proportion to its size. For a few thousand items, that is negligible next to reading the input. A ledger with millions of items would stage only the entries it changes, but the rule stays the same: nothing becomes visible until everything has passed.
Compare with Day 2
On Day 2 you wrote withRollback, which changed the real map and undid the changes on failure. Staging is usually better. A rollback has to undo every kind of change correctly, and between the change and the undo, anyone else reading the map sees the wrong state. With staging, there is nothing to undo.
Practice
Your turn
Write Restock(changes []Line) error on the starter's Ledger, which adds every line or none. Reject a line that would take an item past 100 units, using the overflow-safe comparison from the last lesson. Check a batch that adds 50 drills and 70 tents to 40 tents, which must fail and change nothing, and then a batch that adds 50 drills and 60 tents.
The output should be:
tent would pass 100 units map[tent:40]
<nil> map[drill:50 tent:100]package main
import (
"fmt"
)
type Line struct {
Item string
Quantity int
}
type Ledger struct {
stock map[string]int
}
func main() {
l := &Ledger{stock: map[string]int{"tent": 40}}
fmt.Println(l.stock)
// Write Restock, then check both batches.
}Hint 1: the idea
The structure is the same as Reserve. Only the check and the arithmetic change.
Hint 2: a first step
Clone the stock, loop over the lines comparing line.Quantity > 100-have, and assign the copy to l.stock after the loop.
Worked solution
package main
import (
"fmt"
"maps"
)
type Line struct {
Item string
Quantity int
}
type Ledger struct {
stock map[string]int
}
func (l *Ledger) Restock(changes []Line) error {
const limit = 100
staged := maps.Clone(l.stock)
for _, line := range changes {
have := staged[line.Item]
if line.Quantity > limit-have {
return fmt.Errorf("%s would pass %d units", line.Item, limit)
}
staged[line.Item] = have + line.Quantity
}
l.stock = staged
return nil
}
func main() {
l := &Ledger{stock: map[string]int{"tent": 40}}
fmt.Println(l.Restock([]Line{{"drill", 50}, {"tent", 70}}), l.stock)
fmt.Println(l.Restock([]Line{{"drill", 50}, {"tent", 60}}), l.stock)
}tent would pass 100 units map[tent:40]
<nil> map[drill:50 tent:100]The failed batch had already staged 50 drills, but they never reached l.stock, so drill is not even a key afterwards. The second batch lands exactly on the limit for tents, which checks the boundary at the same time.
Completion is saved in this browser only. It does not measure mastery.