Standard library / sync/atomic

atomic.SwapUint32()

Atomically replace the value and return the old value. Raw pointer APIs require correctly aligned storage; prefer the corresponding typed atomic in new code. Expected stdout: '12\n15\n'.

Formal Syntax & Structure

go syntaxgo
func SwapUint32(addr *uint32, new uint32) (old uint32)

Parameters & Attributes

NameTypeDescription
addr*uint32Pointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently.
newuint32Replacement value.

Return Value

(old uint32)

Previous value.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic")
func main() {  x := new(uint32)  atomic.StoreUint32(x, 12)  fmt.Println(atomic.SwapUint32(x, 15))  fmt.Println(atomic.LoadUint32(x))}
Go Reference