Standard library / sync/atomic

atomic.SwapInt32()

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 SwapInt32(addr *int32, new int32) (old int32)

Parameters & Attributes

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

Return Value

(old int32)

Previous value.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic")
func main() {  x := new(int32)  atomic.StoreInt32(x, 12)  fmt.Println(atomic.SwapInt32(x, 15))  fmt.Println(atomic.LoadInt32(x))}
Go Reference