Standard library / sync/atomic

atomic.SwapUint64()

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 SwapUint64(addr *uint64, new uint64) (old uint64)

Parameters & Attributes

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

Return Value

(old uint64)

Previous value.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic")
func main() {  x := new(uint64)  atomic.StoreUint64(x, 12)  fmt.Println(atomic.SwapUint64(x, 15))  fmt.Println(atomic.LoadUint64(x))}
Go Reference