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

NameTypeDescription
old*TExpected current value for comparison.
new*TReplacement 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())}
Go Reference