Standard library / sync/atomic
atomic.Pointer.CompareAndSwap()
Replace the pointer only when it equals old; compare pointer identity, not pointee contents. Expected stdout: 'true 9\n'.
Formal Syntax & Structure
go syntaxgo
func (x *Pointer[T]) CompareAndSwap(old, new *T) (swapped bool)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| old | *T | Expected current value for comparison. |
| new | *T | Replacement value. |
Return Value
(swapped bool)
Whether the pointer was replaced.
Working Example
Example Snippetgo
package main
import ( "fmt" "sync/atomic")
func main() { a, b := 7, 9 _ = b var x atomic.Pointer[int] x.Store(&a) fmt.Println(x.CompareAndSwap(&a, &b), *x.Load())}