Compare And Delete Keys In sync.Map

CompareAndSwap and CompareAndDelete only write or delete when the stored value still matches, so concurrent updates cannot silently overwrite each other.

GoData Integrity

Code

gosnippet
43 lines
package main

import (
	"fmt"
	"sync"
)

type snapshot struct {
	owner string
	rev   int
}

func main() {
	var m sync.Map
	m.Store("cfg-1", snapshot{owner: "alice", rev: 1})
	m.Store("cfg-2", snapshot{owner: "bob", rev: 1})

	// 只在当前值完全相等时替换(值必须是可比较类型)
	swapped := m.CompareAndSwap(
		"cfg-1",
		snapshot{owner: "alice", rev: 1},
		snapshot{owner: "alice", rev: 2},
	)
	fmt.Println("swap with current value:", swapped)

	// 再用已经过期的旧值比较:失败,说明是值相等而不是无条件覆盖
	stale := m.CompareAndSwap(
		"cfg-1",
		snapshot{owner: "alice", rev: 1},
		snapshot{owner: "alice", rev: 3},
	)
	fmt.Println("swap with stale value:", stale)

	// 只有值仍匹配才删除:不会误删别人刚写入的新版本
	fmt.Println("delete cfg-2:", m.CompareAndDelete("cfg-2", snapshot{owner: "bob", rev: 1}))
	fmt.Println("delete cfg-2 again:", m.CompareAndDelete("cfg-2", snapshot{owner: "bob", rev: 1}))

	m.Range(func(key, value any) bool {
		entry := value.(snapshot)
		fmt.Printf("left: %v owner=%s rev=%d\n", key, entry.owner, entry.rev)
		return true
	})
}

Inside the snippet

Count the function main as the entire surface area of Compare And Delete Keys In sync.Map.

What to watch for

  • Nothing third-party is pulled in; the snippet is dependency-free.

Putting it to use

The labels track each compare-and-write outcome: swap with current value: prints true (cfg-1 still holds alice/rev 1), swap with stale value: prints false because cfg-1 has since moved to rev 2, and delete cfg-2: prints true on the first call and false on the second, after the key is already gone.

Core lines

var m sync.Map

Interactive Tools for This Topic

FAQ

What does Compare And Delete Keys In sync.Map print when run?
The script runs standalone; its 5 labeled outputs include `swap with current value:`, `swap with stale value:`, `delete cfg-2:`.