Standard library / sync/atomic

atomic.Value.CompareAndSwap()

Replace on equality with old. Concrete types must be consistent, new cannot be nil, and equality must be valid. Expected stdout: 'true second\n'.

Formal Syntax & Structure

go syntaxgo
func (v *Value) CompareAndSwap(old, new any) (swapped bool)

Parameters & Attributes

NameTypeDescription
oldanyExpected current value for comparison.
newanyReplacement value.

Return Value

(swapped bool)

Whether replacement occurred.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic")
func main() {  var v atomic.Value  v.Store("first")  fmt.Println(v.CompareAndSwap("first", "second"), v.Load())}
Go Reference