Skip Drop Glue With mem forget
Show drop glue in action and skip it deliberately with std::mem::forget, which consumes a value without running Drop and leaks its heap allocations.
Page 4 of 8
Show drop glue in action and skip it deliberately with std::mem::forget, which consumes a value without running Drop and leaks its heap allocations.
Split Option handling into two closures with map_or_else so the fallback runs only on None, unlike unwrap_or_else where the default is built first.
Iterate an Option directly: Some yields one element, None yields none, and flatten collapses Option layers inside pipelines.
Hand one Vec through take-by-value stages with zero clones; after each move the previous binding is dead, and reusing it is a compile-time E0382 error.
Check palindromes by comparing chars() against chars().rev(), exercising DoubleEndedIterator equality without allocating a reversed copy.
Locate first and last matching indexes with position and rposition, composing parse-failing predicates via is_ok so unparseable entries are skipped.
Read the OS error number behind an io::Error with raw_os_error, and build one back with from_raw_os_error for a faithful round trip.
Let several parents share child nodes through Rc<RefCell<Vec>>: Rc clones share ownership without copying, RefCell mutates inside an immutable shell.
Bind struct fields with ref and ref mut so a pattern borrows in place instead of moving values out, then compare that with borrowing the scrutinee up front.
Take full ownership of removed map data with HashMap::remove_entry, which returns the key and value instead of dropping the key.
Ignore middle elements with rest patterns: .. binds prefixes, suffixes, or both ends, and match dispatches unknown-length slices by shape.
Use Result::inspect_err to log a failure while forwarding the same Result, keeping the error type intact where map_err would rewrite it.
Shadow the std Result with type Result<T> = Result<T, E> so every fallible signature in a module shares one error type.
Find the last occurrence of a byte pattern with rfind, getting the byte index you need for suffix slicing in one call.
Edit a Vec in fixed size batches through chunks_mut, then use chunks_exact_mut and remainder to handle the short trailing batch separately.
Shift bytes inside one slice with copy_within, which tolerates overlapping source and destination like memmove and panics only on out of range indices.
Cut a slice into halves with split_at_checked, which returns None past the end instead of panicking, so length checks fold into one match arm.
Peel a borrowed head plus the remaining slice with split_first to walk sequences without copying or index arithmetic.
Insert substrings at byte indices with String::insert_str and keep indices on char boundaries, since a multi-byte offset makes the call panic.
Run a setup function exactly once across threads with std::sync::Once and call_once, then read the side effects from shared state.
Cut iteration windows with take and skip: take grabs the first n items, skip drops them, and combining both yields offset paging over a slice.
Ask for collection capacity with try_reserve and match TryReserveError, so capacity overflow becomes a recoverable branch instead of a process abort.
Validate conversions with TryFrom: the associated Error type carries the rejection reason, and TryInto lets callers convert without naming the target type.
Collapse None and Err into type defaults with unwrap_or_default: unwrap_or takes an explicit value and unwrap_or_else builds one lazily.
Refresh a Vec in place with clone_from so an existing buffer can absorb new contents without reallocating a fresh clone.
Clone a range of a Vec onto its own end with extend_from_within, which reads the source range before growing so repeats need no temporary buffer.
Drop a Vec capacity down to its length with into_boxed_slice, then convert back with into_vec and note the capacity now equals the element count.
Preallocate Vec storage with with_capacity and reserve so pushes stay inside one allocation; printed len and capacity show exactly when growth fires.
Walk neighbor pairs with windows(2) and batch fixed groups with chunks, two complementary views over the same slice.
Downcast Box<dyn Any> values back to concrete types so heterogeneous registries stay type safe without enums or unsafe code.
Watch Arc::strong_count rise and fall as clones are created and dropped, and use Arc::ptr_eq to prove two handles share one allocation.
Give a trait an associated type so each implementation chooses its own output type, then constrain that output in generic functions.
Track a high water mark across threads with AtomicU64::fetch_max, reading the previous maximum on every update without taking a lock.
Read std::thread::available_parallelism, clamp it to a safe worker count, and run one job per worker with scoped threads.
Capture the current call stack with std::backtrace::Backtrace and inspect its frames to enrich error reports without extra crates.
Merge two BTreeMap values with append, watch duplicate keys take the incoming value, and confirm the source map becomes empty.
Partition a BTreeMap at a key with split_off, inspect both halves, and confirm the boundary key lands in the right-hand map.
Query BTreeSet ranges, neighbors, and extreme elements so sorted unique collections answer boundary questions without linear scans.
Resolve a path containing dot segments with fs::canonicalize, confirm it becomes absolute, and compare it with the original file.
Write chars into a fixed byte buffer with char::encode_utf8 and check that the returned length matches the UTF-8 width.
Parse user keystrokes with char::to_digit so each character is validated in radix before any arithmetic happens.
Wrap keys in std::cmp::Reverse to invert ordering, turning ascending sorts into descending ones and BinaryHeap into a min-heap.
Bound a condition wait with Condvar::wait_timeout_while so a missing notification becomes a deadline instead of a hung thread.
Bucket every character of a password candidate into digit, letter, whitespace, and symbol counts using char classification methods.
Resolve relative paths against env::current_dir so a tool finds the same files no matter which directory launched it.
Decode UTF-16 code units with char::decode_utf16, merging surrogate pairs and reporting unpaired surrogates without panicking.
Hash keys into shards with DefaultHasher for stable in-process bucketing, remembering that the output is not portable across releases.
Bind struct fields straight from match patterns with literals, @ bindings, and range checks, replacing field-by-field if chains.
Give state enums an explicit u8 backing with #[repr(u8)] so variants map to stable wire values and match stays exhaustive.
Read command line arguments from std::env::args, validate flags and values, and return process exit codes without any argument-parsing crate.
Duplicate a file handle with File::try_clone and observe that both handles advance one shared cursor instead of independent positions.
Round-trip floats through f64::to_bits and from_bits to preserve negative zero and NaN payloads that ordinary equality cannot check.
Compare floating point values with a relative tolerance plus an absolute fallback, because exact equality rarely survives arithmetic.
Create a hard link with fs::hard_link, confirm both paths share file data, then modify through one name and read the change.
Move every entry out of a HashMap with drain, filter owned pairs into a Vec, and verify the map is empty afterward.
Insert-or-update in one lookup with the entry API, avoiding double hashing and the borrow-checker workarounds of get-then-insert.
Compare naive squaring with f64::hypot on huge and tiny inputs to show how hypot avoids intermediate overflow and underflow.
Embed a text file into the binary with include_str so templates and manifests are available at runtime without filesystem reads.
Count set bits, measure leading zeros, and round up with next_power_of_two while walking u32 bit positions and rotates.
Concatenate readers with io::chain so headers, bodies, and multiple sources are consumed as one continuous byte stream.
Move bytes between readers and writers with io::copy, including an infinite repeat reader bounded by take and a discarding sink.
Push and pop at both ends of std::collections::LinkedList, then append, split, and iterate lists without contiguous memory.
Parse timestamped log lines with enumerate so every validation error reports the exact source line instead of a bare message.
Derive the shared prefix of string slices by zipping character iterators and cutting at the first mismatch, no extra allocation.
Implement Display and std::error::Error by hand for a config error enum, keeping dependencies off the table while messages stay precise.
Print std::mem sizes and alignments for primitives and a repr(C) struct to reason about padding, cache lines, and buffer layout.
Probe a held std::sync::Mutex with try_lock, match TryLockError::WouldBlock, then acquire it normally after the guard drops.
Order records with Ordering::then_with so the secondary comparison only runs when the primary keys tie, keeping expensive keys out of the hot path.
Match brackets with a Vec stack, pushing opens and popping closes, so mismatches report both the position and the expected closer.
Decompose slices with pattern matching and guards so list shapes like empty, single, and rest are handled without index gymnastics.
Call Rc::try_unwrap while other handles exist to see the error path, drop them, then reclaim the inner String without cloning.
Limit untrusted readers with Read::take so header reads and capped downloads never consume more bytes than the caller allows.
Split byte streams on a delimiter with BufRead::read_until, keeping the separator and handling a final chunk that lacks it.
Build Results with Ok and Err, lift fallible steps into one pipeline, and collect into Result<Vec, E> so any failure sinks the batch.
Propagate errors up the call stack with the ? operator, converting via From so each layer adds context without match boilerplate.
Convert numbers to roman numerals and back with match-driven mapping, exercising both encoding loops and parse validation.
Move a file cursor with SeekFrom start, end, and current offsets to read fixed headers, tails, and records without scanning the whole file.
Find a median without sorting everything: select_nth_unstable partitions the slice in place and returns lower, middle, and higher parts.
Locate the first element failing a predicate in sorted data with partition_point, replacing hand-written binary search loops.
Rotate a slice in place with rotate_left and rotate_right, a cheap way to move a buffered window without allocating or copying manually.
Sort with slice::sort_by_cached_key so each key is computed once per element instead of on every pairwise comparison.
Render control characters with str escape_default, rebuild the same text char by char, and compare it with escape_debug output.
Split text with split_inclusive so each piece keeps its terminator, then contrast the result with lines and a custom predicate.
Implement Sum and Product for a custom type so iterator collect and fold adapters reuse the standard numeric reduction API.
Bounded sync_channel capacity blocks the producer when the consumer lags, giving you backpressure without an external queue crate.
Accept loopback clients with TcpListener, echo each line from a cloned writer, and close cleanly when the peer drops the connection.
Create threads with explicit names and stack sizes through thread::Builder so logs and panic messages identify each worker.
Hand a signal between threads with thread::park and Thread::unpark, which needs no channel and keeps an unpark that arrives before the park.
Store heterogeneous handlers behind Box<dyn Trait> so a registry can dispatch at runtime while each implementation stays a separate type.
Locate the first pair adding up to a target in one pass, remembering seen values in a HashMap instead of rescanning the slice.
Print readable type names with std::any::type_name for generics and nested containers, keeping the output strictly for diagnostics.
Exchange datagrams over loopback with UdpSocket, learning how connectionless peers, packet boundaries, and source addresses behave.
Replace a middle range in place with Vec::splice, keep the removed elements, and reuse the same call with an empty iterator to delete.
Rotate a VecDeque ring buffer into one slice with make_contiguous, compare as_slices before and after, and keep pushing afterward.
Use Wrapping to make overflow deliberate, comparing wrapping_add, checked_add, and saturating_add near the integer limit.
Write several IoSlice buffers through Write::write_vectored, handle partial writes in a loop, and verify the assembled byte stream.
See how closures capture by borrow versus move, and when each mode is forced — the foundation for iterator chains that outlive their scope.
Unwrap single-pattern Options and Results with if let and drain queues with while let, keeping the happy path at full indent depth.
Control what a module exposes with pub and pub(crate), keeping internal helpers invisible while the public surface stays minimal.
Unlock Debug, Clone, PartialEq and Default on structs with a single derive line, and see what each trait actually buys you.