BufWriter Flush Errors Before Drop
Flush a BufWriter explicitly before it drops because Drop discards buffered data and swallows flush errors without any warning.
Page 31 of 50
Flush a BufWriter explicitly before it drops because Drop discards buffered data and swallows flush errors without any warning.
Record counters through shared references with Cell: get and set work under &self with compile-time-only checks, ideal for small Copy state.
Validate untrusted code points with char::from_u32 before building chars: the surrogate range and values past U+10FFFF come back None instead of panicking.
Walk chars with byte offsets using char_indices, where multi-byte characters push offsets ahead of ordinal positions and slicing needs offsets.
checked_add and checked_mul return None on overflow, saturating helpers clamp at the type bounds, and wrapping_add documents modular wraparound.
Command::output runs an external program and hands back stdout, stderr, and exit status as bytes, while a missing binary returns Err instead of panicking.
Parametrize a ring buffer with const generics so capacity N is part of the type: RingBuffer<3> and RingBuffer<4> are distinct, incompatible types.
Fill fixed-size buffers with copy_from_slice, which enforces equal lengths with a panic, and see how runtime-sized copies get an explicit bounds check first.
Implement IntoIterator for a custom collection so for loops consume it: items move out one by one and the original struct is gone after the loop.
Print expressions with dbg! to stderr along with file, line and the evaluated value, keeping the value usable inline so debugging never breaks the data flow.
derive(Default) builds zero-value initializers from field types, and struct update syntax overrides only the fields a caller actually needs.
A container wrapper implementing Deref and DerefMut to a slice gets indexing, len, and in-place sort for free, without exposing the inner field.
Destructure structs and tuples directly in function parameters and for loop bindings so nested data unwraps into named locals right at the binding site.
A custom Display impl formats fields with width, alignment, and zero padding through write!, so println! renders tidy rows directly.
Use div_euclid and rem_euclid when wraparound math must survive negative offsets: the remainder always lands in 0..divisor, unlike the built-in %.
Duration arithmetic scales and splits timeout budgets, checked_add returns None on overflow, and min clamps a deadline under a hard cap.
and_modify updates existing entries in place while or_insert_with lazily builds initial values, completing an upsert with a single hash lookup.
Pair each element with its position using enumerate, add one for one-based numbering, and place it before filter to keep source indexes.
Classify environment lookups with env::var's Result: NotPresent means the key is missing, NotUnicode means the value cannot be read as a String.
Loop over Error::source to print every layer of a failure, ending at the deepest cause so logs keep both the user-facing message and the parser error.
filter_map converts and discards in a single pass: parse failures collapse to None and vanish, successful parses flow on as Some values.
The fmt::Write trait lets write! and writeln! append formatted text into a String without allocating an intermediate value per iteration.
fold carries an initial accumulator of any type while reduce consumes the first element and returns Option, so empty sequences collapse differently.
String::from_utf8 on failure returns the original Vec<u8> inside the error, so callers keep ownership of the data and can repair and retry it.
Implement FromIterator for a histogram type so collect builds it straight from any iterator, then verify the result against a hand-written fold.
Parse a domain value through FromStr with a dedicated error enum that wraps ParseIntError and reports empty, non-numeric, and out-of-range inputs distinctly.
Write one implementation for many types with trait bounds: T: Display for printing, a custom trait for domain behavior, and impl Trait to keep signatures short.
Insert defaults into Options in place: get_or_insert writes only when empty, get_or_insert_with defers the cost, and both return a mutable reference.
Expose borrowed views from struct methods: &self to &str and &[u32] tie to self by elision, while an owned getter clones only when callers must escape.
Collapse consecutive equal values into runs of value and length with one pass over the slice, matching on the previous run to extend or start a new one.
Group sales into a map of vectors with entry or_default: the first occurrence allocates the bucket and later ones borrow it, with sorted keys for stable output.
Query String-keyed maps through borrowed &str keys because Borrow lets get, get_mut and contains_key accept them, avoiding a to_string allocation per lookup.
Mutate every value through values_mut, drop entries with retain, and take ownership of removed values with remove, all without rebuilding the map.
HashSet union, intersection, difference, and symmetric_difference compute set algebra on permission lists; iteration order is random so display sorts.
Overload the plus operator by implementing Add: the impl consumes operands by value, Copy types duplicate, and Neg mirrors the same contract.
Implement Extend for a custom collection so extend accepts any IntoIterator batch; the method takes &mut self and never seizes ownership of the collection.
Implementing Index and IndexMut with tuple keys gives grid[x, y] syntax, while a get method keeps out-of-bounds decisions with the caller.
Embed #[cfg(test)] unit tests beside the code they verify with assert_eq!, assert! and #[should_panic], so cargo test runs them and cargo run skips them.
parse errors expose an IntErrorKind: empty input, invalid digits, and overflow each get a distinct case, and NonZero types turn zero into an error.
Take string parameters with impl Into<String> when ownership is needed and impl AsRef<str> for read-only borrows, so callers pass &str or String freely.
io::Cursor turns a byte vector into a Read/Seek/Write source, so framing and assembly code runs entirely in memory without touching the filesystem.
Parse untrusted address strings into IpAddr and route them into loopback, private, and public buckets so allowlist checks see one normalized classification.
is_sorted checks ascending order under PartialOrd and is_sorted_by_key validates a key such as a timestamp stays monotonic before the data is trusted.
find_map merges filtering and mapping into one pass, yielding the first item whose parse succeeds as Some and None when every candidate fails.
Pick extremes with max_by and min_by using a comparator instead of a key, including the documented tie rules: last maximum, first minimum.
Adapt one-item and no-item cases to any iterator pipeline: iter::once lifts a single value, iter::empty supplies a legal zero-element placeholder.
Generate unbounded sequences with repeat_with: every pull calls the closure once, so take() is what actually makes the stream terminate.
by_ref borrows an iterator so take or filter adapters advance it a bounded amount, leaving the underlying iterator usable for later passes.
copied() duplicates Copy types bit-for-bit from borrowed iterators, while cloned() calls Clone for types like String that own heap data.
Order two sequences element by element with Iterator::cmp: first difference decides, equal prefixes leave the shorter one smaller, is_lt reads as a boolean.
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.