Try Find Stops At The First Failure
try_find runs a fallible predicate and returns the first matching item or the error that stopped the search, in one pass over the data.
Page 14 of 50
try_find runs a fallible predicate and returns the first matching item or the error that stopped the search, in one pass over the data.
zip() over two iter_mut() updates both collections in place; different collections give disjoint mutable borrows that coexist.
Iterator::for_each runs a closure with captured mutable state over a consumed iterator, keeping chained adapters lazy until it executes.
Walk digits in reverse, double every second one and fold 16 into 7, then the total must divide by ten for the card number to validate.
Suppress automatic destructors with ManuallyDrop, taking raw ownership of a value so field order or manual drop() controls when resources release.
Walk rows of A and columns of B with nested loops, multiply term by term and accumulate, producing the classic [[58,64],[139,154]] result.
Build large stack arrays with MaybeUninit::uninit, write elements in place, then assume_init once every slot is provably written.
Exchange two owned values in one operation with std::mem::swap, which moves contents through pointers and never clones payloads.
Average two integers safely with i32::midpoint, which rounds toward negative infinity and never overflows where (a + b) / 2 would.
mpsc::Receiver::try_iter drains every message already queued without ever blocking, so event loops can batch what arrived before doing work.
Option::xor yields Some only when exactly one of the two values is Some, collapsing both-set and neither-set cases to None.
Unwind with typed payloads using std::panic::panic_any, then recover the original value via downcast so non-string error data survives the panic.
Half-open .. ranges compose with len() while ..= keeps the end bound; ranges are values you can test with contains, is_empty, and rev.
Walk slices backwards in fixed batches with rchunks and rchunks_exact, so alignment anchors to the last element instead of the first.
Fold str::replace over known secrets so log lines mask tokens before printing, then assert the masked output contains none of them.
replacen replaces at most n matches from the left, which is how you fix only the first occurrences instead of every one.
Drive a Vec stack with match: binary operators pop two operands, numbers push, and leftover or missing values become typed errors.
slice::contains answers membership with PartialEq, iter().any generalizes to predicates, and windows() plus any() matches ordered subsequences.
str::split accepts char arrays and closures as patterns, so mixed / and \ separators tokenize in one pass without pre-normalizing.
Route narrowing numeric conversions through try_into so out-of-range values return TryFromIntError instead of silently truncating bits.
Widen u64 factors into u128 so a full 128-bit product stays exact, then split it into high and low halves with shifts and casts.
Compute mean with one iterator sum, then variance as the summed squared deviations over the count; this classic sample yields exactly 5, 4, 2.
Share one mpsc receiver across workers through Arc<Mutex>: each thread locks only to pull the next job and exits when the channel closes.
array_positions returns the subscripts of all occurrences of a value in a one-dimensional array, using IS NOT DISTINCT FROM so NULL can be searched too.
Attach the most recent price at or before each trade with a timestamp-filtered LEFT JOIN plus DISTINCT ON, and the ROW_NUMBER window form as an alternative.
Roll up integer permission masks per team with BIT_OR as the union of grants and BIT_AND as what every member shares, then test single bits with an & mask.
Create two identical B-tree indexes differing only in deduplicate_items and compare pg_relation_size, showing how PG13 packs duplicate TIDs into posting lists.
Create one GIN index over an array column plus a scalar text column with the btree_gin operator classes, so containment and equality share a single index.
Count business days between two dates with generate_series over the day range and an ISODOW filter, keeping Monday-Friday and dropping weekends.
The citext extension compares through lower(), so duplicates collapse case-free and PRIMARY KEY uniqueness ignores case without a functional index.
Package related fields into a composite type, build values with ROW(...), and read them back with (col).field — the parentheses are required to disambiguate.
Write one order header and its line items in a single statement by chaining INSERT RETURNING through a data-modifying CTE for atomic parent-child inserts.
currval and lastval read session-local sequence state: currval needs that sequence drawn via nextval in this session, lastval needs any nextval at all.
Run CREATE TABLE and INSERT inside a transaction and roll it back: the table vanishes, proving DDL joins the same transactional story as DML.
Suspend audit triggers with ALTER TABLE ... DISABLE TRIGGER for a bulk load, then re-enable; the USER form spares constraint triggers guarding foreign keys.
ALTER TYPE RENAME VALUE relabels an enum member without touching its sort position, and both a missing old value and an already-used new name fail outright.
Filter outer rows with EXISTS (SELECT 1 ...) as a semi join: matching rows prove existence and stop early without duplicating outer rows like an inner join.
MATCH PARTIAL would let mixed-null composite FKs satisfy the constraint, but PostgreSQL rejects it at transform with "MATCH PARTIAL not yet".
A PL/pgSQL FOR loop can walk a SELECT result row by row: the loop target is assigned each row, and EXIT stops early while keeping the last row readable.
FOR UPDATE OF o locks only the listed table rows in a join; without OF every participating table gets row locks, including pure filter-side tables.
generate_subscripts emits the valid subscript range of one array dimension, and reverse walks it backwards; a missing dimension yields zero rows.
rank(8.00) WITHIN GROUP inserts a would-be value into each ordering and reports its rank directly — the same semantics as a window rank without a frame.
Normalize messy contact strings with INITCAP for word-initial capitalization and TRANSLATE for per-character masking or deletion via an empty replacement set.
Set join_collapse_limit to 1 and the planner stops reordering explicit JOINs, so the written sequence becomes the join sequence whenever you know a better one.
Show one player's standing plus adjacent ranks by computing RANK() for the whole board once and filtering a narrow rank window around the target.
A nested-loop join whose outer keys repeat earns a Memoize node: parameterized inner scans skip work on cache hits, reported in EXPLAIN ANALYZE.
Read EXPLAIN on a partitioned ORDER BY query: Merge Append merges each partition pre-sorted index stream, so LIMIT can stop early without a global sort.
Query the leading column of a two-column btree index and it serves you; filter on the second column alone and the planner cannot enter the leftmost prefix.
Upsert against a partial unique index: ON CONFLICT (email) WHERE deleted_at IS NULL selects the arbiter, and the bare column list fails outright.
Replace a slice in place with overlay(string PLACING string FROM n [FOR len]); omitting FOR uses the inserted string own length as the replaced length.
Take per-group Q1 and Q3 with percentile_cont in a CTE, derive the 1.5x IQR fences, flag rows outside them, and count outliers per group.
PL/pgSQL cannot run a bare SELECT, so PERFORM executes and discards the rows; FOUND then tells you whether the discarded query matched anything.
pg_backend_pid returns the process ID of the server process attached to the current session, matching the pid column in pg_stat_activity and lock diagnostics.
pg_get_constraintdef decompiles a pg_constraint row back into its CONSTRAINT clause, so audits show real definitions rather than hand-copied text.
pg_get_indexdef decompiles a catalog entry back into its CREATE INDEX statement, so migrations and docs can show real DDL instead of hand-copied definitions.
Inspect dead tuples and reusable free space with pgstattuple before and after VACUUM: deletes raise dead_tuple_percent, VACUUM converts them into free_percent.
Require two words adjacent and in order with to_tsquery's <-> (FOLLOWED BY) operator, so 'btree <-> index' misses documents where the pair is swapped.
Compute an exponential moving average with a recursive CTE joining each row to the previous smoothed value; window functions cannot reference their output.
Accumulate edge cost and visited path in a recursive CTE; a strpos guard stops cycles and the outer query keeps each node's cheapest route.
Explode free-form tag lists into rows with regexp_split_to_table behind a LATERAL join; a [,;\s]+ delimiter absorbs the mixed separators split_part preserves.
RETURN NEXT and RETURN QUERY append rows to the result set without leaving the function, so a PL/pgSQL function can mix hand-built rows with whole queries.
Deduplicate uploads by content: a generated sha256 column plus a unique expression index rejects the second identical payload at insert time.
Count real status changes per ticket with LAG plus IS DISTINCT FROM, so repeated heartbeats in the same state never inflate the transition total.
Tokenize a delimited column with string_to_array, filter with = ANY, and rebuild text with array_to_string, where a null string turns empty fields into NULL.
Locate a delimiter with strpos, slice from either end with left and right, and guard the not-found case because left(x, -1) silently trims the tail.
Keep every tie inside the top three per region with RANK() <= 3 over a PARTITION BY window, and contrast the truncating ROW_NUMBER version.
Match word stems still being typed with to_tsquery's :* prefix suffix, so data:* finds data and databases for autocomplete-style search.
Expression indexes reject non-immutable functions, so wrap unaccent in an immutable wrapper pinned to its dictionary and index names for accent-free search.
A NULL team_id means the global default; a unique index on COALESCE(team_id, 0), feature makes two NULL-team rows collide exactly like two rows for team 7.
Read EXPLAIN for window queries: the Sort node feeding WindowAgg, how a matching index removes the Sort, and why distinct windows stack separate nodes.
Compare each month to the same month a year ago: LAG(revenue, 12) assumes a dense series, while a calendar self-join on month - interval stays sparse-safe.
ARIA states expose typed reflection properties such as ariaInvalid and ariaLive, replacing setAttribute strings with compiler-checked assignments.
at() returns T | undefined for out-of-range and negative indexes, replacing optimistic bracket indexing with an honest type you can handle once.
input.list exposes the bound datalist element and datalist.options enumerates suggestions, so free-typed values get a manual membership check.
A diagnostics channel publishes named telemetry that any module can subscribe to, decoupling instrumentation from the code that emits requests.
Two ECDH P-256 key pairs derive identical shared bytes via diffieHellman, which a SHA-256 hash turns into a symmetric session key.
flatMap maps and flattens exactly one array level, so triple-nested arrays stay partially nested and branches must return arrays for a consistent element type.
Type message catalogs with a mapped Renderer so each key accepts exactly its own argument tuple, while satisfies checks every locale without widening keys.
Iterator helpers chain filter, take, and map lazily, but the resulting iterator is single-pass: a drained chain yields nothing on a second consumption.
platform() returns a literal union of platform names, so build-script branches on win32, darwin, and linux are exhaustively checkable.
A mapped as-clause filters interface fields by value type, so PickByValue yields a record with only the string, Date, or array fields.
HTMLMediaElement.play() returns a promise that rejects with named DOMExceptions: AbortError for interruptions and NotAllowedError for autoplay blocks.
New Proxy over a typed target hands every trap the target type, so keyof guards decide what can be indexed and reads log through one place.
Iterate global regexes with a while-exec loop typed as RegExpExecArray | null, reading named groups and tracking lastIndex across matches.
startViewTransition snapshots the old DOM, awaits the update callback, then animates between snapshots; ViewTransition exposes the phases as three promises.
StorageManager.estimate() returns usage and quota for the origin, and persisted() reads whether storage survives eviction pressure.
Intersecting string with an empty object type keeps literal autocomplete while still accepting any runtime string — a plain union cannot do both.
Give structural shapes a static Symbol.hasInstance type predicate so instanceof narrows parsed JSON to LineItem without any shared class prototype.
createTreeWalker with NodeFilter.SHOW_ELEMENT and an acceptNode callback visits only matching elements, keeping the outline walk lazy and allocation-free.
Wrap Map with a TypeMap parameter so each key keeps its own value type — plain Map<K, V> forces one V across every key.
unknown swallows any union it joins while never vanishes from unions and erases intersections — the two bottom types pull in opposite directions.
util.types checks internal slots, so date-like strings, regexp-like objects, and thenables fail their checks while the predicates still narrow types.
A WeakMap typed as WeakMap<RequestOptions, NormalizedOptions> memoizes per object identity, and only objects can ever become keys.
Give each message channel its own discriminated union and postMessage typed payloads with satisfies, so worker replies narrow per kind.
Build an XOR helper from mapped Exclude keys and never-typed optionals so two config branches stay selectable but can never both fill in.
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.