Standard library / sync/atomic
atomic.Uint64.CompareAndSwap()
Atomically replace the value only if it equals old. CAS does not by itself protect multi-variable invariants. Expected stdout: 'true\n15\n'.
Formal Syntax & Structure
go syntaxgo
func (x *Uint64) CompareAndSwap(old, new uint64) (swapped bool)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| old | uint64 | Expected current value for comparison. |
| new | uint64 | Replacement value. |
Return Value
(swapped bool)
Whether the value matched and was replaced.
Working Example
Example Snippetgo
package main
import ( "fmt" "sync/atomic")
func main() { var x atomic.Uint64 x.Store(12) fmt.Println(x.CompareAndSwap(12, 15)) fmt.Println(x.Load())}