Map Lookup Ok Separates Missing From Zero
The two-result map lookup tells a missing key apart from a key stored with its zero value, which plain indexing cannot do.
Page 3 of 8
The two-result map lookup tells a missing key apart from a key stored with its zero value, which plain indexing cannot do.
Sort intervals by start, then extend the last merged span while the next one overlaps, collapsing an unsorted timeline into disjoint ranges.
A method value binds its receiver into a reusable func, while a method expression passes the receiver explicitly as the first argument of the same method.
os.File.Readdirnames returns entry names without FileInfo allocations, a cheaper listing when the code only needs what a directory contains.
Two goroutines trade turns across two unbuffered channels; every handoff is a rendezvous, so the printed ping and pong sequence is fully deterministic.
Each pipeline stage ranges its input and defers close on its own output, so a three-stage chain drains fully and ends without leaks.
Encode non-ASCII mail bodies with mime/quotedprintable so bytes become =XX escapes and soft line breaks keep lines under the 76-character limit.
Draw normal-distributed samples from math/rand/v2 with NormFloat64, scaling the unit variance output to a target mean and standard deviation.
Range variables are copies of each element, so field writes silently vanish; fix it with index writes or a slice of pointers.
reflect.StructTag.Lookup reads custom validate tags per field and distinguishes a missing tag from an empty one, which Get cannot do.
Encode integers by greedy subtraction over descending numeral pairs, then decode by longest-prefix matching the same table back.
Sample runtime.NumGoroutine() before, during, and after a worker batch so a pool that never drains shows up as a count that never returns to baseline.
runtime.Stack writes the current goroutine trace into a caller buffer, and the all=true variant dumps every goroutine for health diagnostics.
Compute SHA-1 digests with crypto/sha1 for legacy fingerprint formats, summing whole payloads or writing chunks through the hash interface.
Walk every case variant of a rune with unicode.SimpleFold, which returns the next equivalent rune and wraps back to the original at cycle end.
slices.All yields index and value pairs as iter.Seq2, so a full pass over a slice can be handed to any function that consumes pairs.
Rank slices element by element with slices.Compare, which reports the first differing element, while CompareFunc applies a custom ordering rule.
slices.SortedFunc returns a freshly sorted copy and leaves the original intact, so audit order survives every presentation sort.
WithGroup prefixes attributes added after it under a dotted path, while With pins attributes onto every later record from that logger scope.
Extract typed fields from fixed-layout strings with fmt.Sscanf, where verbs, literals, and skipped tokens in the format string mirror the input exactly.
ParseInt takes a bitSize ceiling, clamps out-of-range values to that width maximum, and returns ErrRange so 32-bit API fields stay bounded.
strings.TrimFunc strips leading and trailing runes while a predicate holds, with TrimLeftFunc and TrimRightFunc for one-sided variants.
Remove a sync.Map entry and read its old value in one atomic step with LoadAndDelete, avoiding the check-then-delete race of separate calls.
template.Option("missingkey=error") turns missing map keys from silent <no value> output into Execute errors that name the exact key.
time.Ticker.Reset changes the interval between ticks, so a poller can start fast and back off to slower cadence without rebuilding the timer.
AddDate steps one calendar day at a time, so a for loop covers a date range cleanly even when it crosses a month boundary.
Sanitize hostile input with strings.ToValidUTF8, which replaces invalid UTF-8 byte runs with a fixed substitute string and leaves valid text untouched.
Index values as you scan, then look up the complement target-minus-current so each pair is found in one pass with no nested loops.
A type alias is the same type including its method set, while a named type over the same struct starts with an empty method set.
Untyped constants keep arbitrary precision until assignment, so one constant can initialize any integer type that can hold its value.
Walk a byte slice with utf8.DecodeRune, which consumes one UTF-8 sequence per call and reports its width so malformed bytes surface as RuneError.
Align two parallel slices into paired records by index and stop at the shorter side, so leftover names never get fabricated scores.
Compress a byte stream with zlib.NewWriter, then decompress with zlib.NewReader while the underlying Adler-32 checksum validates every roundtrip.
Schedule a one-shot callback on its own goroutine with time.AfterFunc, then observe that Stop on an already-fired timer reports false instead of cancelling.
Update shared flag bitmasks from many goroutines without a mutex: atomic.Or sets bits, atomic.And clears them, and LoadInt64 reads the final snapshot.
Compute GCD and LCM with math/big.Int so values beyond int64 never overflow, and reduce fractions by dividing out the common divisor.
Project struct records onto a key with slices.BinarySearchFunc: hits return the index, misses return the insertion point for sorted inserts.
Skip framed payloads with bufio.Reader.Discard, which drops n bytes without copying them through user buffers and errors on short frames.
Slice one buffer into NUL separated records with bytes.Split and rebuild with bytes.Join, then prove the framing lossless with bytes.Equal.
Collect channel events into batches that flush when full or when a resettable timer deadline expires, so bursts neither pile up unbounded nor drop.
Return functions that capture outer variables: each counter keeps independent state, and assignments inside a closure mutate the captured variable itself.
Test whether a string contains any rune from a class with strings.ContainsAny, then contrast it with IndexAny which reports the matching byte offset.
time.Duration is an int64, so json.Marshal emits integer nanoseconds by default; a custom MarshalJSON emits the 1h30m0s string instead.
cmd.Output takes only stdout, so stderr needs its own buffer: non-zero exits wrap in *exec.ExitError whose ExitCode reports the concrete status.
Read fixed-size records at offsets with File.ReadAt, whose pread semantics let parallel goroutines share one file handle without seeking.
Append each record with File.Sync so the durability contract is explicit: bytes reach stable storage before the call returns, surviving a crash.
Split file paths into directory, base name, and extension with filepath.Dir, filepath.Base, and filepath.Ext so CLI tools can name outputs predictably.
Resolve the process working directory with os.Getwd and join it with filepath.Join so relative config paths become absolute without string concatenation.
Drive an http.HandlerFunc with httptest.NewRequest and a response recorder so handler logic, headers, and error paths run without opening a listener.
Locate substrings with strings.Index and strings.LastIndex, treat the -1 result as not-found, and restart the search after a match to find later occurrences.
Assert at compile time that a concrete type satisfies an interface with var _ Iface = (*T)(nil), so missing methods fail the build before deployment.
json.NewEncoder plus SetIndent streams each value pretty-printed to any writer, appending a newline per Encode without assembling the whole document.
json.Marshal fails on chan and func fields: errors.As recovers *json.UnsupportedTypeError naming the exact Go type, so the wire keeps only encodable data.
Decode only the known fields via map[string]json.RawMessage and pass every other key through untouched, so unfamiliar payloads survive the round trip.
Decode timestamps arriving in several formats by trying layouts from strictest to loosest inside UnmarshalJSON and rejecting unknown shapes.
Extend json decoding without recursion: an alias type keeps the default decode while UnmarshalJSON normalizes fields on the way in.
log.New builds a logger with a prefix and flags; SetOutput swaps the sink to io.Discard to silence or a bytes.Buffer to capture in tests.
MarshalJSON on a pointer receiver is skipped when marshaling the bare value, so the JSON falls back to reflection; pass the pointer to engage it.
Compute square roots, powers, and logarithms with math.Sqrt, math.Pow, math.Log2, and math.Exp, and confirm invalid inputs propagate as NaN.
Create a whole nested directory chain in one call with os.MkdirAll, rely on its idempotence for repeat calls, and clean up the tree with os.RemoveAll.
Keep JSON and multi-line SQL readable in Go source with backtick raw string literals, where backslashes and quotes stay literal and newlines are preserved.
Compute rolling window totals with a running sum: add the entering element and subtract the leaving one instead of rescanning every window position.
Distribute work cyclically over one channel per worker with round-robin indexing, so each goroutine owns a private queue instead of contending on one.
Adapt slices into iter.Seq with slices.Values, then rebuild with slices.Collect, slices.AppendSeq, and maps.Collect so consumers stay decoupled from storage.
Convert a slice to a fixed-size array by value or to a shared array pointer, length-checking first so short frames never panic.
Merge adjacent case-variant duplicates with slices.CompactFunc, using strings.EqualFold as the comparator so GET, get and Get collapse.
Resolve expensive values only when a record is emitted: implement slog.LogValuer so the handler calls LogValue lazily instead of eagerly at call time.
Split log lines and paths with strings.SplitAfter so each returned segment retains its delimiter, making it easy to re-emit the original text exactly.
net.SplitHostPort splits host from port: bracketed IPv6 parses cleanly, a missing port or bare IPv6 returns a *net.AddrError with the reason.
Split a connection string or key-value pair with strings.SplitN so the remainder stays intact as one field instead of being shredded into extra segments.
CutPrefix and CutSuffix split once and report whether the prefix matched, distinguishing an empty value from a completely different token.
Delete from the middle of a slice without shifting: overwrite the slot with the last element and truncate, trading order for constant-time removal.
net.Listen plus an Accept loop gives each connection a goroutine that echoes bytes; SetReadDeadline bounds hung clients and errors.Is(io.EOF) detects closes.
Render the same instant in UTC, a plus-eight zone, and a minus-five-thirty zone without an IANA database, then format a parsed offset back with Z07:00.
Bucket days into report weeks with ISOWeek, where Monday starts the week and year boundaries follow the ISO 8601 ownership rule.
DialUDP pins a UDP peer so Write and Read address the same endpoint; a listener echoes by source address and SetReadDeadline bounds possible drops.
Derive the remaining time budget from a context deadline with time.Until, and report a negative duration once the deadline has already passed.
Printing a credential-bearing URL leaks the password; url.URL.Redacted swaps it for xxxx while User stays usable inside the process.
Turn relative links into absolute ones by resolving each against a base URL: path-only, root-relative, fragment-only, and dot-segment forms all resolve.
Cut a string to a rune limit without splitting multibyte characters: range walks rune boundaries so slicing always lands between characters.
Take an io.Writer parameter instead of writing to os.Stdout directly, so the same report code runs against a buffer in tests and stdout in main.
Read one rune at a time with bufio.Reader.ReadRune, which reports the byte width, then step back with UnreadRune to re-dispatch a character.
Split a byte slice once with bytes.Cut and walk repeated delimiters, receiving before, after, and an explicit found flag.
Use complex128 with math/cmplx to inspect magnitude and phase, multiply by a conjugate, and take the square root of a negative real onto the imaginary axis.
Keep container/heap ordering after a priority change by tracking each element index and calling heap.Fix, then drop an item from the middle with heap.Remove.
Change the GC growth target at runtime with debug.SetGCPercent, which returns the previous value, and inspect recorded pauses through debug.ReadGCStats.
Cap the Go runtime with debug.SetMemoryLimit: read the previous limit, set a soft ceiling, and restore it without a hard crash.
Test names against shell style patterns with filepath.Match, which matches single path elements only and reports malformed brackets as ErrBadPattern.
Split IEEE-754 doubles into sign, exponent, and mantissa fields with math.Float64bits, and see why bitwise comparison is the only reliable NaN identity test.
Define Set[T comparable] over map[T]struct{} with Add, Has, Len, and a non-mutating Union so membership helpers stay type-safe.
Snapshot request headers with http.Header.Clone before mutating a retry copy, so late changes never leak back into the base header.
Render arbitrary bytes as an offset-labeled hex dump with hex.EncodeToString and manual column math, the layout debuggers and protocol tools print.
Neutralize user-controlled text before it reaches HTML: EscapeString turns angle brackets and quotes into entities, and UnescapeString restores them.
Preview the wire format of a request with httputil.DumpRequest so the request line, Host header, and body framing are visible without a packet capture.
Pass your own buffer to io.CopyBuffer so repeated transfers reuse one allocation, then cap the transfer length with io.CopyN and read the remainder.
Expose one byte range of a ReaderAt as its own reader with io.NewSectionReader, so Size and Seek are window relative and the source offset never moves.
Build and split address:port pairs with net.JoinHostPort and net.SplitHostPort so IPv6 hosts get brackets automatically instead of hand-joined strings.
Decode config JSON with DisallowUnknownFields so a typoed or renamed key fails loudly at startup instead of being ignored and leaving zero values behind.
Read Decoder.InputOffset after a failed decode to learn how far the stream was consumed, then slice the original document around that byte offset.
Format JSON for humans or machines with MarshalIndent and Compact: pretty output takes a custom prefix, and Compact squeezes it back to one line.