Standard library / sync/atomic

atomic.Int64.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 *Int64) CompareAndSwap(old, new int64) (swapped bool)

Parameters & Attributes

NameTypeDescription
oldint64Expected current value for comparison.
newint64Replacement 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.Int64  x.Store(12)  fmt.Println(x.CompareAndSwap(12, 15))  fmt.Println(x.Load())}
Go Reference