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.

GoResilience

Code

gosnippet
35 lines
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

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:`.