Standard library / sync/atomic

atomic.Pointer.Swap()

Atomically replace the pointer and return the old pointer. Expected stdout: '7 9\n'.

Formal Syntax & Structure

go syntaxgo
func (x *Pointer[T]) Swap(new *T) (old *T)

Parameters & Attributes

NameTypeDescription
new*TReplacement value.

Return Value

(old *T)

Previous pointer or nil.

Working Example

Example Snippetgo
package main
import (  "fmt"  "sync/atomic")
func main() {  a, b := 7, 9  _ = b  var x atomic.Pointer[int]  x.Store(&a)  old := x.Swap(&b)  fmt.Println(*old, *x.Load())}
Go Reference