Sync.Map LoadOrStore And Range
Guard a shared cache with sync.Map: LoadOrStore inserts atomically when absent, Load reads with comma-ok, and Range walks entries without blocking writers.
Code
package main
import (
"fmt"
"sync"
)
func main() {
var cache sync.Map
// LoadOrStore:原子地「不存在才写入」,返回 (现有值, 是否已存在)
actual, loaded := cache.LoadOrStore("session:42", "alice")
fmt.Println("first insert loaded:", loaded, "value:", actual)
// 键已存在时不会被覆盖:mallory 写不进去
_, loaded = cache.LoadOrStore("session:42", "mallory")
fmt.Println("second insert loaded:", loaded)
if v, ok := cache.Load("session:42"); ok {
fmt.Println("hit:", v)
}
cache.Store("session:7", "bob")
cache.Store("session:9", "carol")
cache.Delete("session:42")
// Range:遍历期间其他 goroutine 仍可读写;顺序不做保证
cache.Range(func(key, value any) bool {
fmt.Printf("entry %v -> %v\n", key, value)
return true // 返回 false 可提前终止遍历
})
}What the code does
Sync.Map LoadOrStore And Range comes down to the function main.
Using it
Running the file prints labeled results such as first insert loaded:, second insert loaded:, hit: — each operation’s effect is visible in the output.
Key statements
return true // 返回 false 可提前终止遍历
var cache 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.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.SemVer Range CheckerCheck whether a semantic version satisfies an npm-style range such as caret, tilde, comparison sets, wildcards, or hyphen ranges.
FAQ
- What does Sync.Map LoadOrStore And Range print when run?
- No setup needed: run the file and look for labeled lines like `first insert loaded:`, `second insert loaded:`, `hit:` in the output.
Report a problem with this exampleOpens a pre-filled issue on GitHub.