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.

GoResilience

Code

gosnippet
32 lines
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

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.