Standard library / sync
sync.Map.CompareAndSwap()
Replace a stored value only if it equals old. The old value must be comparable. Expected stdout: 'true\n2\n'.
Formal Syntax & Structure
go syntaxgo
func (m *Map) CompareAndSwap(key, old, new any) (swapped bool)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| key | any | Comparable map key, or a package-specific comparable context key. |
| old | any | Expected current value for comparison. |
| new | any | Replacement value. |
Return Value
(swapped bool)
Whether replacement occurred.
Working Example
Example Snippetgo
package main
import ( "fmt" "sync")
func main() { var m sync.Map m.Store("a", 1) fmt.Println(m.CompareAndSwap("a", 1, 2)) v, _ := m.Load("a") fmt.Println(v)}