The shop keeps each customer's cart in the map carts, and its routes make new carts with makeCart: {"owner": "ana", "items": []}. Go has no default values for parameters, so a route that has no list passes nil for items; the PUT route passes a saved list to bring a cart back. An AI assistant wrote it like this:
var defaultItems = make([]string, 0, 10)
func makeCart(owner string, items []string) *Cart {
if items == nil {
items = defaultItems
}
return &Cart{Owner: owner, Items: items}
}
Then Ana opened her cart and found Ben's pen where her mug had been. defaultItems is made once, when the program starts: one array with room for 10 items. Every cart made with nil gets a slice over that same array, and append writes into its free room. Ben's cart was empty, so his pen went into the first slot, the very slot that held Ana's mug. This is a shared default. A smaller example:
var tags = make([]string, 0, 10)
func addTag(tag string) []string {
return append(tags, tag)
}
a := addTag("new") // [new]
b := addTag("sale") // [sale]
fmt.Println(a, b) // [sale] [sale]: the same slot again
The fix: make a new empty slice inside the function, when items is nil. Lines inside a function run at every call, so every cart gets a slice of its own. Use []string{}, not nil: encoding/json writes a nil slice as null, and an empty cart should show []. A list that was passed in, like a restored cart, is kept as it is.
Your makeCart must give these answers:
POST /carts/ana/items {"product": "Mug"} → 201 {"owner": "ana", "items": ["Mug"]}
POST /carts/ben/items {"product": "Pen"} → 201 {"owner": "ben", "items": ["Pen"]}
POST /carts/ana/items {"product": "Lamp"} → 201 {"owner": "ana", "items": ["Mug", "Lamp"]}
GET /carts/ben → 200 {"owner": "ben", "items": ["Pen"]}
GET /carts/eva → 200 {"owner": "eva", "items": []}
PUT /carts/chloe {"items": ["Plant", "Teapot"]} → 200 {"owner": "chloe", "items": ["Plant", "Teapot"]}
Your task: write makeCart so a cart made with nil gets a new empty slice of its own, and a cart made with items keeps that slice.
Assignment
Follow the Coding Tutorial to write makeCart with a new empty slice made inside the function when items is nil.
Hint
The new slice must be made inside makeCart, in an if items == nil, so it runs at every call. When AI code fills a missing value from one package-level slice or map, ask whether every call shares it.
Free plan: 30 tutor messages. PRO is unlimited.
