Cycle Repeats An Iterator With A Take Bound
Turn a finite slice iterator into an endless stream with cycle, then bound consumption with take and hop around the stream with nth.
Page 6 of 8
Turn a finite slice iterator into an endless stream with cycle, then bound consumption with take and hop around the stream with nth.
Watch values flow through an iterator pipeline with inspect, logging each stage without altering the stream that map and filter_map continue to consume.
Reverse traversal with rev works on any DoubleEndedIterator, so Vec iterators, ranges, and string chars can be consumed back to front.
skip(offset).take(size) slices any page out of an iterator, and requests past the end yield the remaining elements instead of panicking.
Sample every Nth element with step_by, which always keeps the first item and walks the rest at a fixed stride, so uniform sampling never needs grouping.
Split an iterator of pairs into two independent vectors with unzip, then recombine them with zip, whose result follows the shorter input side.
Initialize process-wide state on first access with LazyLock: the constructor runs once, later reads borrow the same static, and no unsafe appears anywhere.
Use loop as an expression: break hands a value out of the retry cycle, every break must agree on the type, and a budget arm supplies the fallback.
Uppercase strings and byte buffers in place with make_ascii_uppercase: no allocation and only a-z are touched, leaving non-ASCII characters untouched.
Break a HashMap apart by ownership: into_keys hands each key to the consumer, into_values does the same for values, without cloning anything.
map_while fuses mapping and truncation: iteration stops at the first item whose parse fails, so only the valid prefix of the feed is ever touched.
A per-character match with literal, range, and wildcard arms turns a raw string into tokens: symbols emit immediately, word chars accumulate.
Drive a tiny config parser with match arms, one branch per line shape — comments, section headers, key=value pairs — and report unknown keys as warnings.
Locate every occurrence of a substring with match_indices, which yields byte offsets and matched &str slices, and yields nothing at all when nothing matches.
Matching an owned enum moves payloads out of variants; matching a reference borrows them. Both shapes appear here, with use-after-move left to the compiler.
Matching on &mut hands each arm a mutable borrow, letting match arms patch enum payloads and Option values without rebuilding them.
Unwrap Result Option pairs in one match: Ok Some yields the value, Ok None means a missing record, and Err carries the query failure.
Convert Option<String> into Option<&str> with as_deref before matching so arms compare string literals while the owned value stays usable afterward.
A tuple match dispatches on status and attempt count together: one arm pairs a variant with a concrete value and guards refine the boundary.
Merge two sorted slices with peekable iterators: peek compares the front runners without consuming, next advances the loser, and remainders drain at the end.
Bound channel waits with recv_timeout, branch on Timeout and Disconnected separately, and probe without waiting using try_recv.
MutexGuard owns the lock for its lifetime: probe with try_lock, call drop to end the critical section early, or bound the guard with a plain block scope.
A panic while holding the lock poisons the Mutex, but PoisonError still hands back the guard data through into_inner for controlled recovery.
Round sizes up to alignment boundaries with next_multiple_of for buffers and pages, with a checked variant that returns None instead of panicking.
Turn zero-rejection into a type with NonZeroU32 and NonZeroUsize: construction returns Option, division by the value cannot panic, and the compiler knows it.
Cache a derived value inside a struct with OnceCell: get_or_init computes once under &self, later reads reuse it, and set after init errors.
Open a log with create and append options so writes always extend the file, propagate io errors with ?, and clean the file up when the demo ends.
Narrow optional values with Option::filter and answer present-and-valid questions with is_some_and, both driven by a single predicate closure.
Propagate a missing field through an Option-returning function with the question-mark operator, so one absent value collapses the whole lookup.
transpose swaps Option and Result nesting so errors surface outward, and flatten unwraps one layer of wrapped Results after the swap.
Evict a queued value only when a predicate holds with Option::take_if — the slot clears in place when it fires and stays untouched when it does not.
Pair two independently parsed values with Option::zip so a missing separator or one failed parse rejects the whole input without nested if-let chains.
A single arm can list several values with | and nest them inside tuple or enum patterns, so grouped classification stays one exhaustive match.
Implement custom sort rules by matching the three Ordering variants that cmp returns, breaking ties on a second field before handing the comparator to sort_by.
Get wrapped results and an overflow flag in one call: overflowing_add and overflowing_mul return the value modulo the type plus a carry boolean.
panic::set_hook installs a handler that runs before unwinding, turning every panic into one structured crash line with file and line attached.
PhantomData carries a unit type at zero runtime cost, so Meters and Feet are distinct compile-time types and mixing them simply fails to compile.
from_str_radix parses integers in bases 2 through 36 and to_digit converts single characters, returning typed errors when a digit is invalid for the radix.
fs::read_dir returns an iterator of io::Result entries, so each directory item is handled separately and file types come without extra stat calls.
Passing &mut to a function is an implicit reborrow: the borrow returns when the call ends, and &mut *value narrows the type without transferring.
try_borrow and try_borrow_mut return Err instead of panicking, showing at runtime that RefCell allows many readers or one writer but never both.
and_then chains parse, validate, and transform steps so the first Err short-circuits the pipeline while Ok values flow into the next fallible function.
retain_mut hands each element a mutable reference: mutate first, then decide to keep or drop, finishing update and pruning in a single pass.
Return closures from functions with impl Fn plus move, capturing state into the closure instead of borrowing stack locals that would not outlive the call.
Functions can hand back an owning iterator typed as impl Iterator: callers depend only on the item type while the internal chain stays swappable.
RwLock lets any number of readers hold guards together while writers exclude everyone; try_read fails while a write guard is alive.
slice::binary_search returns Ok with the index on a hit and Err with the insertion point on a miss, which inserts a new element keeping order.
Turn a borrowed slice into a fixed-size array with try_into; exact lengths move through, mismatches surface as TryFromSliceError you map to your own error.
Order tickets by several fields at once with a tuple sort key, pairing the ascending priority with Reverse around the descending age value.
Sort floating-point data with f64::total_cmp, the IEEE-754 total order that gives NaN a deterministic position instead of panicking on incomparable values.
split_once cuts at the first delimiter and returns Option of two borrowed slices, while rsplit_once cuts from the right for URLs and paths.
Count word frequencies by feeding split_whitespace into a HashMap entry, then rank the aggregated pairs with a tie-broken sort for reproducible output.
Bound how many pieces splitn produces so the final piece keeps the untouched remainder, and use rsplitn to slice from the right edge instead.
Read stdin in a loop with read_line, clear and reuse one buffer, treat EOF as zero bytes, and match the parse Result so bad input retries instead of panicking.
Indexing a &str by bytes panics off char boundaries; get returns None instead, and is_char_boundary backs a safe truncation helper.
Choose split_terminator over split when a trailing separator should end the record, not start an empty one — the classic newline-difference.
Watch the plus operator move the left String into the result, and switch to format! or push_str when the original value must stay usable.
Drop unwanted chars from a String in place with retain: char-safe iteration, no new allocation, and the original buffer is reused across passes.
Preallocate with with_capacity, append with push_str, and reserve headroom so string building runs in amortized constant time without repeated reallocation.
strip_prefix and strip_suffix return Option of the remaining borrowed slice, so unmatched input becomes None instead of a silently wrong string.
Two mutable borrows of different fields coexist because the borrow checker proves they are disjoint, while a whole-struct method would collide.
Use take_while_inclusive when the item that fails the predicate is itself meaningful — the iterator stops after yielding the boundary element.
thread_local! gives each thread its own RefCell-backed value, so counters started in a spawned thread begin from zero instead of sharing main's state.
Move owned data into thread::spawn closures, then recover each result through join, which also surfaces worker panics as Err instead of crashing the caller.
try_fold takes a closure returning Result: the first failing element aborts the whole fold, while plain fold has no early-exit channel.
try_for_each folds a fallible closure over an iterator and returns on the first Err, so later items are never touched after a failure.
Compute absolute differences with abs_diff so unsigned results never panic, and use unsigned_abs on i32 deltas before casting to usize.
Running every validation rule and flattening the Option failures into one Vec reports all problems at once instead of stopping at the first.
Compare Vec append, which empties the source by moving elements, with extend_from_slice cloning and extend consuming an iterator chain.
Push into a Vec that grows on demand or into one preallocated with with_capacity, watching capacity() so reallocation points are observed rather than guessed.
Vec::drain removes a range and hands the elements to an owning iterator, shortening the Vec while the collected items become independent owned data.
Grow, truncate, and reset byte buffers in place with resize and fill: growing needs Clone for new slots, truncation drops the tail, fill wipes stale bytes.
Cut length with truncate or empty a Vec with clear, while capacity stays reserved — reuse the allocation for the next batch instead of reallocating.
VecDeque pushes and pops at both ends in constant time, serving queue-style head removal and stack-style tail removal from one structure.
Give a child a Weak back-reference instead of a strong Rc so parent-child loops never leak: downgrade stores it, upgrade returns Option when the parent lives.
Fixed-size arrays carry their length in the type, so a signature can force wrong lengths out at compile time, while Vec grows and both borrow as one slice.
Recursive enums need a known size, so Box stores child nodes behind a heap pointer while match walks the owned tree to sum values and measure depth.
Wrap risky calls in std::panic::catch_unwind so a panic comes back as an Err payload and the supervisor loop keeps running instead of aborting.
When a mutation needs data from the same collection, first collect targets by shared borrow, then mutate after collect ends the borrow.
Return std::process::ExitCode from main so the process exit status reflects the outcome, with custom non-zero codes for script and CI checks.
Decode byte vectors with from_utf8_lossy so invalid bytes become U+FFFD instead of panicking, against the strict from_utf8 that keeps the bytes in Err.
Pick iter for shared borrows, iter_mut for in-place edits, and into_iter to consume the collection — each form decides what survives the loop.
chain concatenates two iterators lazily, and iter::once appends a single tail element without allocating an intermediate collection.
Pick extremes from iterators with max_by_key and min_by_key, which return the last maximum and first minimum and collapse to None on empty input.
Split parsed rows once with Iterator partition, then unwrap the valid half and unwrap_err the invalid half to keep values and reasons separate.
Answer existence questions with any and all and locate items with find and position — all four stop at the first matching element.
Thread an accumulator through scan so each output derives from prior state, and stop the whole iterator early by returning None.
Since Rust 1.88 let chains join if-let bindings with boolean checks in one condition, so earlier bindings feed later patterns without nesting.
Dispatch commands by matching string literal patterns, always ending with a catch-all arm since the compiler cannot prove str exhaustiveness.
Let structs borrow their fields instead of owning them, propagating the input lifetime through constructors so views stay zero-copy.
take_while keeps the matching prefix and skip_while drops it — both stop at the first failing item, unlike filter which scans everything.
Remove neighbors with dedup on a sorted vector, keep unsorted segments honest with plain dedup, and dedup_by_key on a chosen field.
remove keeps element order but shifts every later item, while swap_remove fills the gap with the last element in constant time and scrambles order.
Immutable borrows may coexist, but a live borrow blocks mutation until its last use, which NLL then releases for an exclusive mutable borrow.
Choose the destination type and collect fills it: pairs become HashMap or ordered BTreeMap entries, and duplicate values collapse inside HashSet.
Return borrowed data untouched and allocate only when a rewrite is needed with Cow<str>, keeping one API for both zero-copy and owned results.
Implement Drop on a guard struct so cleanup code runs when the value leaves scope, either at block end or through an explicit drop call.
Log failures at the propagation boundary with Result::inspect_err, which runs a side effect and hands the untouched error back to the ? operator.
Classify io failures by ErrorKind instead of string matching: fall back to defaults on NotFound, refuse on PermissionDenied, and surface anything else loudly.
Build iterators without a struct using std::iter::from_fn for closure state and successors for first-element-plus-step sequences like counters and Fibonacci.