Move Closures Own Their Captured State
Build a counter factory whose move closure takes ownership of the captured count, so each returned closure carries independent mutable state between calls.
Page 17 of 50
Build a counter factory whose move closure takes ownership of the captured count, so each returned closure carries independent mutable state between calls.
Receiver implements Iterator, so a for loop consumes it by value and ends exactly when every sender has been dropped.
Clone an mpsc Sender so multiple producer threads feed one channel, then poll the receiver with try_recv and handle its Empty and Disconnected outcomes.
Annotating helper functions with #[must_use] turns ignored return values into unused_must_use warnings, while let _ = marks deliberate discard.
needs_drop tells generic code at compile time whether T runs cleanup, so arenas and containers can branch their teardown without runtime checks.
Match a non_exhaustive enum with a trailing wildcard arm so variants added upstream later degrade gracefully instead of breaking the match.
Bind the same field from several enum variants in one arm with | patterns, provided every variant gives the binding the same concrete type.
Use r# to name a field, variable, and function after a Rust keyword such as type, then confirm the raw syntax is only needed at definition and call sites.
Read::bytes turns a reader into an iterator of io::Result<u8>, letting per-byte read errors be handled inside the loop instead of aborting the stream.
Inspect a Result without consuming it: as_ref turns Result<T, E> into Result<&T, &E> so the check can branch on contents and still hand the value onward.
Result::is_ok_and evaluates a predicate only when Ok and is_err_and only when Err, letting callers branch on outcomes without unwrapping.
Probe Send and Sync bounds with compile-time assertions so thread-safety guarantees are checked when types change, not in production.
When every receiver is dropped the send fails: SendError::into_inner hands back the owned value so the producer can retry or park the message.
chunk_by groups consecutive elements whose pairwise predicate holds, turning runs of related values into slices without allocating.
Join a string slice into a separator-delimited String, convert numeric slices with map + to_string first, and see how empty and single-element slices behave.
Order records with sort_unstable_by_key using a cheap extracted key, and compare it with sort_by_key to see that unstable sorting does not preserve ties.
Build a title-case converter from split_whitespace and char methods, uppercasing the first character of each word while lowercasing the rest.
Annotate helper functions with #[track_caller] so Location::caller inside them reports the caller file, line, and column for better diagnostics.
Give each borrowed field its own lifetime parameter so one source may end while the other still lives, instead of forcing both to share 'a.
extract_if removes elements matching a predicate in place and yields them as an iterator, so pruning and collecting happen in one pass.
Read boundary elements through first and last instead of indexing, so an empty Vec yields None rather than a panic, and mutable variants edit in place.
Grow or shrink a Vec with resize_with, whose closure produces each new element from captured state, and observe that shrinking skips the closure entirely.
Compute year/month/day gaps with age(), which borrows calendar days across month ends instead of assuming fixed-length months.
Raise per-column sampling with SET STATISTICS so ANALYZE keeps a longer most_common_vals list and finer histograms for skewed or long-tail columns.
CHAR(n) pads stored values with spaces and ignores trailing spaces in comparisons and length(), while VARCHAR(n) keeps every byte.
One out-of-range row fails the entire INSERT statement: CHECK constraints evaluate every row and the whole batch rolls back, so pre-validate imports.
CHECK evaluates each row in isolation — it cannot query other rows — so cross-row invariants need UNIQUE or exclusion constraints instead.
CREATE INDEX IF NOT EXISTS compares names only: an existing index with different columns silently wins, so migrations can run on the wrong shape forever.
Run a data-modifying CTE chain that archives the current row and inserts its replacement, sharing one snapshot and one commit.
Prepare the candidate set once in a CTE, then reference it twice in a self-join with a shift_id guard so each overlapping pair is reported exactly once.
Chain INSERT ON CONFLICT with RETURNING inside a CTE so the guaranteed row keys feed a follow-up join in the same statement.
Chain two CTEs so one statement ranks submitted items and joins reviewer assignments, producing the review queue in a single snapshot.
Layer a CTE and window functions: CORR measures ad-spend to revenue correlation inside each region partition instead of one pooled number.
EXTRACT(DOW) numbers Sunday as 0 through Saturday 6, while ISODOW follows ISO 8601 with Monday 1 through Sunday 7.
Self-join pg_index metadata to find indexes whose key column lists are identical on the same table, so redundant write amplification can be dropped.
ON DELETE CASCADE walks the whole reference chain: grandchild rows vanish with the root, and one RESTRICT deeper down blocks the entire delete.
ON DELETE SET DEFAULT rewrites child keys to the column default, and the delete fails outright when that default does not satisfy the foreign key.
Renaming a referenced natural key ripples into child rows under ON UPDATE CASCADE, while the NO ACTION default and RESTRICT reject the update instead.
Count consecutive funnel conversions with LAG(event, n) over user-ordered events: a step only counts when its predecessor steps happened.
GiST indexes answer nearest-neighbor queries directly: ORDER BY location <-> point returns rows from nearest to farthest without a sort step.
A partial index only helps queries whose WHERE clause implies the index predicate, so the planning output decides whether it gets used.
A failed CREATE INDEX CONCURRENTLY leaves an INVALID index that still taxes writes; find it in pg_index, drop it, and rebuild.
Interval literals accept both verbose strings and ISO 8601 durations like P1DT2H, and the two forms compare equal for the same span.
JOIN USING coalesces the shared column into one output column while ON keeps both sides, and NATURAL joins implicitly on every shared name.
GIN indexes serve containment on jsonb, but scalar equality on payload->>'key' needs a btree expression index built on that exact expression.
Emulate the unimplemented IGNORE NULLS by pre-filtering NULLs in a subquery, then streaming last_value over a narrowed frame per ticker.
Data-modifying CTEs and the outer query share one snapshot: the outer SELECT still counts rows a WITH DELETE removed; only later statements see them gone.
Partial index predicates must be IMMUTABLE, so now() inside the WHERE is rejected; gate the index on a stable status column and leave time filters to queries.
A DEFAULT partition absorbs rows no other partition accepts, and blocks CREATE TABLE ... PARTITION OF until conflicting rows are moved out.
Updating a partition key value triggers row movement: the row vanishes from the old partition and appears in the new one automatically.
Create a partitioned index and per-partition partial indexes, then confirm each child carries its own index entry in pg_indexes.
One WITH list may hold several RECURSIVE items: walk the manager chain upward and fan out to all reports in the same query, then union the labeled halves.
Cycle-tainted hierarchy walks terminate when the recursive CTE uses UNION: duplicate rows are discarded, so a repeated node produces nothing new.
Aggregate the strictly previous rows with ROWS BETWEEN n PRECEDING AND 1 PRECEDING: the current row never influences its own look-back statistic.
var_pop divides by n while var_samp divides by n-1, so one-row samples return NULL under samp but 0 under pop, and the same split applies to stddev.
Cross-row CHECK is implementation-dependent; the portable guard is a trigger that counts rows itself and must lock the zone first or inserts race past the cap.
NOT VALID only applies to foreign-key, CHECK, and not-null constraints, so a UNIQUE addition must scan and dedupe the whole table in the same statement.
Turn a small hand-written tuple list into an inline WITH ... AS (VALUES ...) CTE and LEFT JOIN against it, so unmatched parameters return zero rows.
security_invoker views execute with the caller's privileges, so row level security follows the caller instead of being bypassed by the view owner.
Measure the elapsed days between consecutive visits with LAG and a date difference, converting row order into per-user inter-event gaps.
Window calls cannot nest inside one SELECT level: compute the inner ranking in a CTE, then rank that output in the outer query.
COUNT, MAX, and AVG OVER (PARTITION BY) stamp every row with its group's aggregates, so detail rows survive alongside group totals.
Compute each group median with PERCENTILE_CONT WITHIN GROUP, including interpolated even-count values, then join the aggregate back per row.
Compare RANK and DENSE_RANK on tied totals: RANK leaves gaps after ties while DENSE_RANK numbers every distinct value consecutively.
rank, row_number, lag, and ntile ignore the frame clause entirely, while aggregates and first_value honor it — same frames, different results.
Restart running totals per month with PARTITION BY date_trunc expression keys, so each bucket starts its own cumulative sum beside the all-time total.
Widen or preserve tuple literals deliberately: plain arrays widen to primitives, as const keeps each element its literal type for lookup tables.
Give a class several constructor signatures over one implementation so call sites stay typed whether they pass raw parts or a parsed record.
Call checkVisibility once, or with checkOpacity and checkVisibilityCSS options, to ask whether an element is actually rendered instead of guessing.
Save a JSON config file with fs.promises.writeFile and read it back with readFile, keeping one async round trip for the whole config lifecycle.
Detect Node, worker, or browser once with globalThis and typeof guards so isomorphic code picks the right branch without touching window or global.
Load config as a JSON module with `with { type: 'json' }` so mislabeled specifiers fail at build time instead of becoming runtime surprises.
Type rest tuples as [T, ...T[]] so first() returns T instead of T | undefined and zero-length arrays fail compilation instead of crashing later.
Remove the nullable side of unions with NonNullable so lookup helpers can throw on absence and their return types still check out.
Derive argument tuples and return types from existing functions so wrappers and handlers stay in sync when the original signature changes.
Force one shared instance with a private constructor and a static getter, so new Logger() cannot compile outside the class.
Accept readonly T[] at function boundaries so sort, reverse, and push fail to compile instead of mutating a caller's array behind its back.
Mark factory parameters readonly so reordering or deduplicating an input array fails to compile instead of corrupting a shared table.
Await requestFullscreen with options, handle its rejection paths, and follow fullscreenchange plus exitFullscreen to track element state.
Verify a lookup table against a target shape with satisfies while keeping literal narrowing, so missing or misnamed rows fail at compile time.
Constrain CSS length strings to number-plus-unit shapes with template literal types, so invalid units fail compilation before parsing.
Constrain size strings to number-plus-suffix template literal types so a mistyped unit fails compilation before any parsing code runs.
Track the visual viewport during keyboard overlap with resize and scroll listeners, and keep the focused input inside the visible surface.
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.