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

NameTypeDescription
keyanyComparable map key, or a package-specific comparable context key.
oldanyExpected current value for comparison.
newanyReplacement 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)}
Go Reference