Swap Immutable Snapshots With atomic.Pointer
Publish updated RouteTable structs via atomic.Pointer.Swap so readers holding earlier Load pointers keep reading consistent immutable snapshots.
Code
package main
import (
"fmt"
"sync/atomic"
)
type RouteTable struct {
Version int
Primary string
}
func main() {
var current atomic.Pointer[RouteTable]
current.Store(&RouteTable{Version: 1, Primary: "us-east"})
// Reader holds an immutable snapshot before the swap
pinned := current.Load()
fmt.Printf("pinned snapshot: v%d -> %s\n", pinned.Version, pinned.Primary)
// Writer swaps in a brand-new immutable struct without mutating v1
prev := current.Swap(&RouteTable{Version: 2, Primary: "eu-west"})
fmt.Printf("swapped out: v%d -> %s\n", prev.Version, prev.Primary)
latest := current.Load()
fmt.Printf("latest snapshot: v%d -> %s\n", latest.Version, latest.Primary)
fmt.Printf("pinned unchanged: v%d -> %s\n", pinned.Version, pinned.Primary)
fmt.Println("same pointer:", pinned == prev)
}Execution breakdown — Swap Immutable Snapshots With atomic.Pointer
Swap Immutable Snapshots With atomic.Pointer comes down to the function main.
What to watch for
- Zero third-party libraries needed; language built-ins handle every step.
Using it
Signature: func main()
The demo output is labeled (pinned snapshot: v, swapped out: v, latest snapshot: v); each label names the call that printed it.
Key statements
prev := current.Swap(&RouteTable{Version: 2, Primary: "eu-west"})
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Pointer EvaluatorEvaluate RFC 6901 JSON Pointer strings against a JSON document to extract the referenced value, with tilde-slash escape handling.
FAQ
- What does Swap Immutable Snapshots With atomic.Pointer print when run?
- Run it as a complete program — the output lines carry labels such as `pinned snapshot: v`, `swapped out: v`, `latest snapshot: v`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.