Go delete after owner check
Release a locker after checking that its current owner is the student returning it.
A simple example
delete after owner check
- Start with A = 1
- Do this Remove A if its value is 1
- Result A is absent
Syntax
delete(claims, key)
Run these examples in Go
Save one example at a time as main.go. Use Go 1.21 or later.
go run main.goRelease a locker only for its recorded owner
A school uses locker numbers as keys and student names as values. When Mira returns her locker, the desk clears the assignment only if the current register still names Mira.
package main
import (
"fmt"
)
func main() {
claims := map[string]string{"L2": "Mira"}
if owner, found := claims["L2"]; found && owner == "Mira" {
delete(claims, "L2")
fmt.Println("Released")
}
}
Released
Locker L2 belongs to Mira, so the register accepts the return.
Return a locker key
A locker has a single claim and its registered holder returns the key. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
Keep a reserved headset
A different student tries to release the only headset claim. The clerk removes the claim only when the recorded owner matches the claimant. How many claims remain?
What to watch for
delete has no return value. Check the owner before removing the entry.