Vec Iteration Patterns
Pick between iter, into_iter, and iter_mut deliberately — each gives a different element type and consumes the vector differently.
Page 5 of 8
Pick between iter, into_iter, and iter_mut deliberately — each gives a different element type and consumes the vector differently.
Since Rust 2021, for loops consume arrays by value through IntoIterator; contrast iter() borrows with owned iteration and moves.
Demonstrate as conversions honestly: wide integers truncate, signed bit patterns reinterpret, char maps to its code point, floats saturate.
Compare tokens with eq_ignore_ascii_case to skip allocations, and know when to fall back to full Unicode to_lowercase for non-ASCII text.
Iterate a BTreeMap and get keys in ascending order every run, so reports and diffs are deterministic without collecting and sorting first.
Test characters with is_ascii_digit, is_alphanumeric, and friends, then partition or filter strings by those predicates in one pass.
Declare typed constants, const fns, and a static array sized by a const expression so the backoff table is computed during compilation.
Implement From for each upstream error so one error type owns every failure shape, and let the question mark operator convert automatically at each call site.
Write a manual Debug impl with debug_struct to redact secrets and mark unlisted fields with finish_non_exhaustive instead of leaking them.
File::create_new fails with ErrorKind::AlreadyExists when the path exists, giving you race-free exclusive creation for lock files and IDs.
Replace nested map-then-flatten chains with flat_map, turning one input into several outputs inside a single lazy iterator pass.
Fix decimal places with {:.N}, force signs, zero-pad widths, and switch to scientific notation with {:e} and {:E} format specifiers.
Render integers in binary, octal, and hex with the b, o, and x format specs, including zero padding and the # prefix variants.
Classify paths with fs::metadata: is_dir and len for existing entries, ErrorKind::NotFound for missing ones, no read of the file content.
Derive PartialEq, Eq, and Hash on a struct so whole-value lookups work in HashMap, then bucket repeated keys with the entry API.
Observe that HashMap visits entries in an order that can differ per run and per process, then produce stable output by sorting keys before iterating.
Parse length-prefixed frames with read_exact, which reports UnexpectedEof instead of a silent short read when the wire ends mid-frame.
Adapters behind an iterator can emit values after their first None; fuse() turns that first None into a permanent end so pipelines stay safe.
Right-pad short rows to a fixed width by chaining repeat_n onto the row iterator; the count saturates to zero when the row is already full.
Flatten a collection into one String with join, which works on slices of str, String, and even Option values, without hand-rolled loops or format! chains.
Rust labels live in the loop-type position ('search: for …) so break 'search unwinds every nesting level at once and continue 'rows discards one outer round.
Match against references and destructure through them so borrowed data stays in place, with bindings that keep ownership at the owner.
Group related types in an inline module, expose only what the API needs through pub and pub(crate), and reach it with use paths.
Read file_stem and extension, swap suffixes with set_extension and with_extension, and see None for files that never had one.
next_if consumes the next item only while a predicate holds, so parsers can peel digits or an exact character with no manual peek bookkeeping.
Store one string as Rc<str> and hand out cheap pointer clones to many structs, with strong_count confirming the single shared allocation.
Generate fixed-width separators, indentation, and repeated patterns with str::repeat, which allocates once instead of concatenating in a loop.
saturating_add, sub, and mul clamp at MIN and MAX instead of panicking or wrapping, unlike checked (Option) and overflowing (carry) variants.
Reuse a name with a new type through shadowing, contrast it with mut, and let block expressions produce values like if/else chains.
Cut byte ranges out of a String in place with drain, collect the removed part, and keep indices on char boundaries to avoid panics.
Test string membership with contains, starts_with, and ends_with, and remember that a pattern argument accepts chars as well as literal strings.
Convert between epoch offsets and unix seconds with duration_since, which returns Err instead of a negative duration when the clock runs backwards.
Declare a trait with required and default methods, implement it for multiple types, and call it through a generic function bound.
Clean user input with trim and trim_end before parse, because stray whitespace and line endings are the most common reason valid numbers fail to parse.
Use tuple keys in HashMap to count consecutive character pairs; derive ordering by collecting and sorting entries for stable output.
Give verbose types readable names with plain and generic aliases — no new type is created, so aliases stay interchangeable with the original.
Use insert and remove for order-preserving edits in the middle of a Vec, and know the O(n) shift cost that separates them from push, pop, and swap_remove.
Take impl IntoIterator at function boundaries so callers pass vectors, arrays, or ranges directly, and the function only needs into_iter and sum.
Write read-only helpers against &[T] and mutating helpers against &mut [T]; Vecs and arrays deref-coerce into the borrowed slice the function actually needs.
Arc::make_mut clones the shared value only while other owners hold references, then mutates in place once the Arc is uniquely owned.
Fill a fixed-size array element by element with array::from_fn, getting an inline, stack-allocated table computed from each index at construction.
Apply array::map to fixed-size buffers: the result keeps the same length at compile time, can change element type, and never touches the heap.
Validate characters with is_ascii_hexdigit to accept only 0-9 a-f A-F, then decode each accepted char through to_digit with radix 16.
Capture the matched value with @ while range and or-patterns still select the branch, so one binding serves both branch decisions and output formatting.
fetch_add with Relaxed ordering keeps increments atomic without cross-operation ordering, and Release stores pair with Acquire loads to publish data.
Barrier::wait blocks until every thread in the group arrives, releasing them together each round so phase boundaries stay aligned across workers.
Replace two-arm true-or-None matches with then_some for eager values and then for lazy closures, and extend validation lists straight from the results.
Register heterogeneous closures in one Vec of Box<dyn FnMut> and fire them later, because boxed trait objects erase the distinct closure types.
BTreeMap keeps keys ordered so range queries return inclusive and exclusive windows without sorting, with first and last key access at logarithmic cost.
Stream file lines with BufReader and lines(), propagate io errors with ?, and tally valid versus invalid records without loading the whole file.
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.