Degrees And Radians With to_degrees And to_radians
Math APIs speak radians while users speak degrees; to_radians and to_degrees translate at the boundary and round-trip within one ulp.
Page 3 of 8
Math APIs speak radians while users speak degrees; to_radians and to_degrees translate at the boundary and round-trip within one ulp.
mul_add computes a*b+c with a single rounding; on huge factors the naive a*b+c loses the final unit that fused math keeps.
Pack integers into fixed byte arrays with to_be_bytes and parse them back with from_be_bytes, keeping big-endian wire layouts exact.
Build the transpose of a grid with nested iterators: one value per row per output column, with the original grid only ever borrowed.
Store fn pointers in a HashMap and dispatch commands by name, handling unknown operations through the Option returned by get.
Interleave two sequences by zipping until the shorter side runs out and chaining the leftover tail, so no element from either input drops.
io::IsTerminal reports whether stdin and stdout are attached to a TTY, letting CLIs choose colored interactive output or plain text for pipes.
advance_by and nth(n) move an iterator forward by a position count without allocating anything for the items they skip.
One fold pass tracks min and max together, instead of walking the data twice with separate min and max calls.
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.
Box errors as dyn Error + Send + Sync so failures from worker threads carry context and still move across thread boundaries.
Store eight boolean flags in a single u8 with shift and mask operations, then read, set, clear, and toggle individual bits without any allocation.
str::bytes iterates u8 while chars iterates Unicode scalars, so counts differ for multi-byte runes and len() reports the byte total directly.
Rewrite camelCase identifiers to snake_case by scanning chars and inserting an underscore before each uppercase letter.
Parse single characters into digits with to_digit under any radix, composing with iterators to read hex input without allocations.
collect::<Option<Vec<_>>> returns None at the first None, so parsing a list of digits or fields fails as a whole without manual early exits.
Propagate a stop signal through recursive visitors with std::ops::ControlFlow, so the first failing node halts the whole walk without Result plumbing.
Add next and next_back to a custom inclusive range so consumers can walk it forward with next or in reverse with rev, one step at a time.
Struct fields drop in declaration order while locals drop in reverse, so paired resources release in a predictable, observable sequence.
An enum over an mpsc channel carries typed commands; the worker matches Add, Greet, and Stop arms, and recv returning Err ends the loop naturally.
Call f64 math methods — sqrt, powf, powi, log2, ln, and exp — directly on number literals and combine them with the constants in std::f64::consts.
Dispatch on a leading byte with slice patterns and byte literals, binding payload fields per opcode while unknown codes fall into a catch-all arm.
Finalize an upload by renaming the staged temp file to its object key: same-directory rename is atomic and a missing stage maps to a clear NotFound error.
u32::try_from(char) reports Infallible as its error type: an empty match compiles because that Err arm is logically unreachable and unwrap never panics.
Measure wall-clock work with Instant::now and elapsed, and rely on Instant's monotonic guarantee so later reads never precede earlier ones.
Implement IntoIterator for a reference so for loops receive borrowed items, the collection survives the loop, and generic fns can consume &shelf directly.
Prepend one lazily computed element to a stream with once_with: the closure runs only when the iterator is consumed, never at construction time.
Verify two sequences agree element-wise under a custom predicate with eq_by, so whitespace-normalized comparisons and length mismatches need no index loop.
Duration implements Sum, so one iterator pass adds step timings; dividing by the step count with Div<u32> yields the average without a manual loop.
Yield mutable references from a custom iterator without unsafe: mem::take swaps the remaining slice out, split_first_mut peels one element off the front.
Join a panicking worker and recover its payload: JoinError::is_panic plus into_panic downcasts the boxed Any back to the message the thread panicked with.
Kadane's scan folds over deltas, resetting negative running sums and tracking the best seen, handling all-negative and empty inputs.
str::lines recognizes and and strips them, yielding no trailing empty line, while split('\n') keeps and produces one.
Define a declarative macro_rules! macro that expands k => v pairs into HashMap insert calls, giving collection literals without repeating boilerplate.
Majority vote tracks a candidate and counter in one pass, then verifies the candidate truly exceeds half the input before returning it.
Match counts.entry(key) on Occupied and Vacant: vacant slots insert, occupied slots mutate in place via get_mut, one probe per lookup.
Build a counter factory whose move closure takes ownership of the captured count, so each returned closure carries independent mutable state between calls.
Receiver implements Iterator, so a for loop consumes it by value and ends exactly when every sender has been dropped.
Clone an mpsc Sender so multiple producer threads feed one channel, then poll the receiver with try_recv and handle its Empty and Disconnected outcomes.
Annotating helper functions with #[must_use] turns ignored return values into unused_must_use warnings, while let _ = marks deliberate discard.
needs_drop tells generic code at compile time whether T runs cleanup, so arenas and containers can branch their teardown without runtime checks.
Match a non_exhaustive enum with a trailing wildcard arm so variants added upstream later degrade gracefully instead of breaking the match.
Bind the same field from several enum variants in one arm with | patterns, provided every variant gives the binding the same concrete type.
Use r# to name a field, variable, and function after a Rust keyword such as type, then confirm the raw syntax is only needed at definition and call sites.
Read::bytes turns a reader into an iterator of io::Result<u8>, letting per-byte read errors be handled inside the loop instead of aborting the stream.
Inspect a Result without consuming it: as_ref turns Result<T, E> into Result<&T, &E> so the check can branch on contents and still hand the value onward.
Result::is_ok_and evaluates a predicate only when Ok and is_err_and only when Err, letting callers branch on outcomes without unwrapping.
Probe Send and Sync bounds with compile-time assertions so thread-safety guarantees are checked when types change, not in production.
When every receiver is dropped the send fails: SendError::into_inner hands back the owned value so the producer can retry or park the message.
chunk_by groups consecutive elements whose pairwise predicate holds, turning runs of related values into slices without allocating.
Join a string slice into a separator-delimited String, convert numeric slices with map + to_string first, and see how empty and single-element slices behave.
Order records with sort_unstable_by_key using a cheap extracted key, and compare it with sort_by_key to see that unstable sorting does not preserve ties.
Build a title-case converter from split_whitespace and char methods, uppercasing the first character of each word while lowercasing the rest.
Annotate helper functions with #[track_caller] so Location::caller inside them reports the caller file, line, and column for better diagnostics.
Give each borrowed field its own lifetime parameter so one source may end while the other still lives, instead of forcing both to share 'a.
extract_if removes elements matching a predicate in place and yields them as an iterator, so pruning and collecting happen in one pass.
Read boundary elements through first and last instead of indexing, so an empty Vec yields None rather than a panic, and mutable variants edit in place.
Grow or shrink a Vec with resize_with, whose closure produces each new element from captured state, and observe that shrinking skips the closure entirely.
Borrow a mutable inner value straight out of an Option with as_deref_mut, editing &str in place while None stays None.
Promote a one-shot heap map to a program-lifetime static table with Box::leak, trading an allocation for read-only global lookup without cloning.
Aggregate hits in a BTreeMap whose natural key order makes reports deterministic, with range iteration and entry upserts and no explicit sorting step.
Read a BufReader in zero-copy chunks with fill_buf and consume, bounding each read to the buffer capacity instead of allocating a Vec per segment.
Collect a mapped iterator into Result<Vec<i32>, _>: one bad element short-circuits the whole collect with the first error and leaves no partial vector.
Match against named constants with path patterns, and see why a lowercase identifier in the same position silently becomes an always-matching binding.
Mark one enum variant with #[default] so derive(Default) selects it, and Settings::default() starts in a sane state.
Pass &String as &str through deref coercion: Box<String> and &Vec also coerce, so function boundaries take &str or slices without callers copying.
Implement a Hasher with FNV-1a and hand BuildHasherDefault to HashMap so two identical builds share one bucket layout instead of seeded per instance.
Classify floats with f64::classify and match FpCategory: NaN, infinite, zero, subnormal, and normal each get an arm.
Read and mutate slices without panics: get returns Option<&T>, get_mut returns Option<&mut T>, and plain indexing stays for provably in-bounds access.
Take disjoint mutable borrows of two HashMap entries in one call with get_many_mut, so transfers can hold both sides at once.
Implement the Write trait for a counting sink that tallies bytes and newlines, returning the consumed length that write! and write_all rely on.
Wrap arbitrary failure strings into a real io::Error with Error::other, then classify both custom and filesystem errors by their ErrorKind.
Pick the iteration mode deliberately: iter borrows read-only, iter_mut borrows mutable for in-place edits, into_iter consumes and hands out ownership.
Override size_hint on a custom iterator so collect reserves capacity up front, and compare it with a wrapper that hides the hint and grows as it pushes.
Chain filter and map without doing work: adapters build a pipeline that collect, sum, or a for loop drives, so no intermediate collections appear.
Flatten nested sequences in one pass with flat_map: pages of items or comma-split lines collapse into a single iterator and empty inner values vanish.
Apply the elision rules that let one-input functions and methods omit lifetimes, and see why picking one of two borrows still needs an explicit lifetime.
Fold consecutive exit codes into named bands with range patterns: literal ranges like 64..=78 become match arms, and char ranges classify tokens too.