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.
Publish updated RouteTable structs via atomic.Pointer.Swap so readers holding earlier Load pointers keep reading consistent immutable snapshots.
Encode binary tokens cleanly with base64.RawURLEncoding and hex.EncodeToString, showing how unpadded decoders reject trailing equals signs.
Decode fixed-width BigEndian packet headers and length-prefixed payloads with encoding/binary, rejecting truncated frames or magic mismatches.
Inspect leading bytes with bufio.Reader.Peek without advancing the cursor, then split records via ReadBytes while handling a trailing io.EOF.
Combine container/list with an index map to promote accessed entries in O(1) time and record evicted keys when inserting past max capacity.
Attach a cancel hook with context.AfterFunc to close an in-flight resource, and unregister the hook via defer stop() when work finishes early.
Configure csv.Reader with a pipe Comma, hash Comment, and TrimLeadingSpace, then normalize whitespace and re-export the rows as TSV.
Build a nested multi-error tree with errors.Join and fmt.Errorf %w, then traverse both Unwrap() []error and Unwrap() error branches recursively.
Mount a narrow directory view with fs.Sub, prune temporary folders via fs.WalkDir and fs.SkipDir, and verify parent escapes fail.
Order pending retry jobs by earliest deadline and ID tie-breaker using container/heap, popping due work and pushing backed-off attempts.
Sign canonical webhook payloads using crypto/hmac with SHA-256 and validate hex signatures in constant time via hmac.Equal against tampering.
Wrap an io.WriterAt buffer with io.NewOffsetWriter to write header, payload, and footer sections at independent offsets using io.Writer and Seek.
Copy bytes from a producer goroutine through io.Pipe and propagate failures explicitly via CloseWithError instead of a silent EOF.
Wire io.TeeReader into io.MultiWriter so a single io.Copy hashes incoming bytes with SHA-256 and CRC-32 while writing two output destinations.
Parse RFC 5322 headers, sender and recipient lists, timestamps, and message body streams from an in-memory reader using net/mail.ReadMessage.
Defer compiling a regexp until first validation with sync.OnceValue, so concurrent goroutines share one compiled matcher without manual locks.
Combine a runtime slice of channels into []reflect.SelectCase using reflect.Select, handling default fallback and pruning closed channels safely.
Inspect env and default struct tags via reflect.StructTag.Lookup to populate typed string, int, and bool fields from a key-value map cleanly.
Maintain a fixed-capacity latency window in container/ring, overwriting the oldest slot and ignoring unfilled nil nodes during summary scans.
Combine cmp.Or fallback defaults, maps.Clone per-batch isolation, and slices.Chunk iteration to dispatch fixed-size slices cleanly.
Assert ascending monotonicity with sort.SliceIsSorted, then use sort.Search to match usage metrics against threshold tiers and handle overflows.
Build structured telemetry lines in a preallocated byte slice using strconv.AppendInt for decimal and hex fields while keeping buffer capacity fixed.
Coordinate concurrent goroutines with sync.Map.LoadOrStore so only one winner initializes each shared key while peers receive the existing value.
Register custom text/template FuncMap helpers and contrast missingkey=zero against missingkey=error so absent keys either default cleanly or fail.
Parse MIME headers with net/textproto ReadMIMEHeader and decode dot-stuffed text blocks via DotReader, stopping cleanly at the terminator line.
Stop an active or expired time.Timer and drain its channel with a non-blocking select before Reset so stale ticks never fire early.
Inspect identifier runes against unicode.Latin, unicode.Cyrillic, and custom Range16 tables via unicode.In to block mixed-script spoofing attempts.
Resolve relative, protocol-relative, and external redirect strings against a base net/url.URL, then enforce same-scheme and same-host checks.
Scan raw strings via utf8.DecodeRuneInString so invalid byte runs (RuneError with width 1) are separated from genuine U+FFFD runes (width 3).
Perform 128-by-64 division with bits.Div64 and subtract-with-borrow using bits.Sub64, completing the wide-arithmetic pair next to Add64 and Mul64.
Define package-level errors with errors.New, wrap them through layers, and match the sentinel with errors.Is even when the message has changed.
Show that a panic in one goroutine crashes the whole process, and demonstrate the recover-in-worker pattern that contains it.
Keep the K largest values from an unbounded stream using a min-heap that evicts its smallest element whenever the bound is exceeded.
Convert a Seq2 into next/stop functions with iter.Pull2 so the consumer pulls key-value pairs on demand instead of being driven by the producer.
Unmarshal a JSON array straight into []struct with json tags, then print one formatted field per record to prove the shape.
Decode a JSON object into a struct with json tags so missing fields keep their zero values and type mismatches surface as explicit errors.
Layer an override map on top of defaults so present keys win and absent keys keep their default, a common config merge shape.
Group a record slice by a computed key into map[string][]T, using the zero value of a missing key so no existence check is needed.
Walk the representable float grid with math.Nextafter — one step toward a target from below or above — to test rounding and spacing behavior.
Tally each Unicode code point with a map keyed by rune, then report counts in sorted order so the histogram is deterministic.
Race a slow channel receive against a closed done channel so a cancelled waiter exits immediately instead of blocking forever.
Escape arbitrary strings into safe double-quoted literals with strconv.Quote and recover them with Unquote, keeping control characters intact.
Locate characters by predicate instead of literal: IndexFunc reports the first match, ContainsFunc answers membership, LastIndexFunc scans from the end.
Measure how many times a substring appears with strings.Count, including the overlapping-free rule that distinguishes it from a manual scan.
Classify runes into printable categories with unicode.IsGraphic and IsPrint, seeing exactly which control and space characters each accepts.
Canonicalize repeated strings through unique.Make so equal values share one handle, cutting duplicate allocations in hot paths.
Round-trip runes through unicode/utf16 and see IsSurrogate, Encode, and DecodeRune classify lone surrogates versus legal pairs.
Replace the manual for-i-less-than-b.N loop with b.Loop on Go 1.24: iteration count, timer reset, and memory stats are handled automatically.
Decompress an embedded bzip2 stream with compress/bzip2, whose streaming reader needs no output size — the package ships decompression only.
Compress and decompress bytes with compress/lzw, where the byte order and literal width are parameters that both ends must share.
Classify context errors with errors.Is: canceled callers, exceeded deadlines, and healthy contexts each report a distinct outcome.
Build cmd.Env from os.Environ plus overrides so children see staged configuration, and filter secrets out of the inherited environment before spawn.
Split PATH-style environment values with filepath.SplitList, which uses the OS list separator, and rejoin them without guessing the delimiter.
Register a flag whose parsing logic is a plain callback with flag.Func, so repeatable values accumulate without a custom flag.Value type.
Compare floats through a small epsilon instead of ==, since 0.1+0.2 != 0.3 while positive infinity still equals itself.
Implement fmt.Formatter so Printf hands your type the verb and flags, letting it render its own %v, %+v, and %q output.
Encode interface-valued fields with gob by registering each concrete type, so the decoder can rebuild the right variant from the transmitted name.
Turn panics into errors by recovering in a deferred function and switching on the panic value: runtime errors implement error, strings stay strings.
Implement fmt.GoStringer so the %#v verb prints a redacted summary for credential-bearing types instead of leaking password fields into debug logs.
Unmarshal into any and type-switch on map[string]any, []any, float64, and string branches to inspect JSON whose structure is only known at runtime.
Accept payloads that arrive as an {"orders": [...]} envelope or a bare array by trying two Unmarshal targets in order and falling back cleanly.
Intersect two count bags with min-per-item so shared stock reflects overlapping quantities, not just which names both maps contain.
Aggregate tickets into map[string]map[string]int keyed by region then status, sorting outer keys because map range order is randomized.
Compute MD5 digests with crypto/md5 in one-shot and streaming forms, and keep the warning: known collisions make it unfit for any security purpose.
Parse and build host:port pairs with netip.AddrPort, keeping address and port as typed fields instead of splitting strings by hand.
Pick url.PathEscape for a single path segment and url.QueryEscape for a query value, since the two sets of reserved characters differ.
Show the unsynchronized counter that the race detector flags under go run -race, and the mutex-guarded version that converges on the same workload.
Write struct fields by name with reflect.Value.FieldByName after CanSet and AssignableTo checks, so generic form or config binding fails with clear errors.
Build every (size, color) pair from two slices with a generic cross product helper, not just the index-aligned pairs that zip produces.
Take head and tail windows of at most n items with clamping, and see that the windows remain views into the same backing array.
Split one slice into info and warn groups with two append targets, preserving original order in each group without mutating the source.
Reorder items by an index permutation after validating length and uniqueness, so bad indices fail before any element is moved.
Walk two slices with one index per side to test whether a short sequence appears in order inside a longer event stream.
Deduplicate records by a projected key — lowercased email — keeping each first occurrence instead of requiring exact whole-value equality.
Rewrite JSON log fields with slog.HandlerOptions.ReplaceAttr: rename the time key, lowercase levels, and redact sensitive keys before they reach output.
Locate a target in sorted data with sort.Find, whose three-way cmp returns the same signs as strings.Compare and reports the exact insert point on a miss.
Store signed integers in one to ten bytes with binary.PutVarint, and walk the buffer back with binary.Varint to recover each value and its width.
Turn a block cipher into a stream with cipher.NewCTR: one keystream per direction, XORKeyStream both ways, and why an IV must never repeat under the same key.
Group anagrams by their sorted rune key so listen, silent, and enlist share one map entry, with sorted keys keeping printed output deterministic.
Distribute dynamic work with one atomic counter: each worker claims the next index, writes its own slot, and exits when exhausted.
A slice used as a stack matches every closer against the top opener; leftovers at the end or a mismatched pop both mean the sequence is broken.
Track the lowest buy price in one pass and sell later for the largest gain, so one scan finds the best profit without nested loops.
Flatten a stream of streams with bridge: consume <-chan (<-chan T), drain each source under the same done, and yield one merged result channel.
Read newline-framed input with bufio.Reader.ReadString, which returns the delimiter attached and reports io.EOF when the stream ends mid-line.
Hit bufio.ErrTooLong on a line past the 64KiB default, then raise the cap with Scanner.Buffer so oversized records still parse.
A generator goroutine yields values through a receive-only channel, closes it on exit, and watches a done channel so early consumers never leak the producer.
len on a buffered channel reports pending items and cap reports capacity; a nil channel reports zero for both and blocks forever on receive.
Chmod changes a file's permission bits and Stat reads them back, so secret files can drop to owner-only 0600 before any data is written.
Reset a map or slice in one builtin call: clear empties every map key and stores zero values while keeping slice length and capacity.
Compose multi-key ordering with cmp.Compare inside cmp.Or: the first non-equal field decides, and equal elements keep their relative input order.
Squeeze two pointers inward always moving the shorter wall, since it caps the area, so the maximum container is found in one pass.
Attach request-scoped data with context.WithValue, keyed by an unexported struct type so package boundaries cannot collide and lookups stay type-safe.
Point csv.Reader and csv.Writer at a semicolon delimiter with the Comma field, so European dialect files roundtrip without any manual splitting.
Define a custom error with an Unwrap method so errors.Unwrap peels one layer at a time and errors.Is still matches the sentinel cause underneath.
Solve daily-wait-until-warmer with a monotonic stack of unresolved indexes, settling each in O(1) amortized instead of scanning forward from every day.
Resolve command names through exec.LookPath, handle the ErrNotFound path, and see why names containing separators bypass the PATH search.
Feed a child process through cmd.Stdin with any io.Reader, avoiding temp files while the command consumes the data as a stream.
Register in-process metrics with expvar Ints and Maps, retrieve them by name with Get, and walk every published variable with Do — no metrics library.
Write into fixed regions of a file with os.File.WriteAt: disjoint offsets compose independently and a later patch rewrites only the targeted byte range.
os.FileMode packs type and permission bits: String renders them rwx style, Perm strips the type bits, and IsDir or IsRegular classify the mode.