Standard library / sync/atomic
atomic.SwapInt64()
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 SwapInt64(addr *int64, new int64) (old int64)Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| addr | *int64 | Pointer to the shared variable; satisfy architecture alignment requirements and use atomic access consistently. |
| new | int64 | Replacement value. |
Return Value
(old int64)
Previous value.
Working Example
Example Snippetgo
package main
import ( "fmt" "sync/atomic")
func main() { x := new(int64) atomic.StoreInt64(x, 12) fmt.Println(atomic.SwapInt64(x, 15)) fmt.Println(atomic.LoadInt64(x))}