Standard library / sync/atomic

atomic.SwapPointer()

Replace an unsafe.Pointer and return the old pointer atomically. Expected stdout: '7 9\n'.

Formal Syntax & Structure

go syntaxgo
func SwapPointer(addr *unsafe.Pointer, new unsafe.Pointer) (old unsafe.Pointer)

Parameters & Attributes

NameTypeDescription
addr*unsafe.PointerPointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently.
newunsafe.PointerReplacement value.

Return Value

(old unsafe.Pointer)

Previous pointer.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic"  "unsafe")
func main() {  a, b := 7, 9  _ = b  var x unsafe.Pointer  atomic.StorePointer(&x, unsafe.Pointer(&a))  old := atomic.SwapPointer(&x, unsafe.Pointer(&b))  fmt.Println(*(*int)(old), *(*int)(atomic.LoadPointer(&x)))}
Go Reference