Standard library / sync/atomic

atomic.Bool.CompareAndSwap()

Set the boolean only when it matches old. Expected stdout: 'true true\n'.

Formal Syntax & Structure

go syntaxgo
func (x *Bool) CompareAndSwap(old, new bool) (swapped bool)

Parameters & Attributes

NameTypeDescription
oldboolExpected current value for comparison.
newboolReplacement value.

Return Value

(swapped bool)

Whether the replacement occurred.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic")
func main() { var x atomic.Bool; fmt.Println(x.CompareAndSwap(false, true), x.Load()) }
Go Reference