LoadAndDelete Pops Entries Atomically
Remove a sync.Map entry and read its old value in one atomic step with LoadAndDelete, avoiding the check-then-delete race of separate calls.
Code
package main
import (
"fmt"
"sync"
)
func main() {
var leases sync.Map
leases.Store("node-a", "10.0.0.11")
leases.Store("node-b", "10.0.0.12")
// LoadAndDelete:取值与删除一步完成,返回旧值与是否命中
if old, ok := leases.LoadAndDelete("node-a"); ok {
fmt.Println("released:", old)
}
_, present := leases.Load("node-a")
fmt.Println("node-a still present:", present)
// 重复释放:第二次命中失败,不会误删别人的记录
if old, ok := leases.LoadAndDelete("node-a"); ok {
fmt.Println("double release:", old)
} else {
fmt.Println("double release rejected")
}
// 对照 Load+Delete 两步法:两步之间值可能被并发替换
if old, ok := leases.Load("node-b"); ok {
leases.Delete("node-b")
fmt.Println("two-step removed:", old)
}
// 收尾:Range 遍历剩余条目
leases.Range(func(key, value any) bool {
fmt.Println("remaining:", key, "=", value)
return true
})
}How it works
LoadAndDelete Pops Entries Atomically reduces to the function main.
Caveats
- Self-contained — imports go no further than what the runtime provides.
Using it
Each step the file takes is announced in the output: released:, node-a still present:, double release:.
The key statements that remain
var leases sync.Map
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- What does LoadAndDelete Pops Entries Atomically print when run?
- Invoke the file as-is — the `released:`, `node-a still present:`, `double release:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.