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
| Name | Type | Description |
|---|---|---|
| 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/atomic")
func main() { var v atomic.Value v.Store("first") fmt.Println(v.CompareAndSwap("first", "second"), v.Load())}