Atomic Pointer Swap Without Type Assertions
Store and swap typed snapshots with atomic.Pointer: loads need no type assertion, and CompareAndSwap matches pointer identity rather than field values.
Code
package main
import (
"fmt"
"sync/atomic"
)
type Limits struct {
MaxConns int
Timeout int
}
func main() {
// 泛型 atomic.Pointer:元素类型固定为 *Limits,读取无需类型断言
var current atomic.Pointer[Limits]
current.Store(&Limits{MaxConns: 100, Timeout: 30})
snapshot := current.Load()
fmt.Println("initial:", snapshot.MaxConns, snapshot.Timeout)
// 整体替换为新快照:读方要么看到旧值要么看到新值,永远不会看到半更新
current.Store(&Limits{MaxConns: 200, Timeout: 10})
fmt.Println("updated:", current.Load().MaxConns, current.Load().Timeout)
next := &Limits{MaxConns: 300, Timeout: 5}
// CompareAndSwap 比较的是指针同一性,不是字段值:
// 新分配的等值指针不算命中
swapped := current.CompareAndSwap(&Limits{MaxConns: 200, Timeout: 10}, next)
fmt.Println("cas with equal-valued pointer:", swapped)
// 用 Load 拿到的真实指针做 CAS 才会成功
prev := current.Load()
swapped = current.CompareAndSwap(prev, next)
fmt.Println("cas with loaded pointer:", swapped, "->", current.Load().MaxConns)
}Inside the snippet
Atomic Pointer Swap Without Type Assertions comes down to the function main.
What to watch for
- Nothing arrives from a registry; the language ships every API used.
Putting it to use
Entry signature: func main()
The demo output is labeled (initial:, updated:, cas with equal-valued pointer:), so each line traces straight back to the statement that printed it.
The core lines of the flow
swapped := current.CompareAndSwap(&Limits{MaxConns: 200, Timeout: 10}, next)
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.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.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 Atomic Pointer Swap Without Type Assertions print when run?
- Running the file directly is enough — expect labeled output lines such as `initial:`, `updated:`, `cas with equal-valued pointer:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.