Rust Complete Reference Index
Select any item below to open its full syntax specification, parameters, and live example.
attribute
#[cfg] — Compile only selected code#[cfg(predicate)]
Attach a configuration condition to an item. If the condition is false, that item is removed from the configured source. Unlike cfg!, this can exclude references to unavailable APIs. all, any and not combine predicates; Cargo features and target configuration are separate concepts.
Result: Conditional item inclusion.
Compiler flags: --cfg bytemind_preview.
Expected output (not executed): 'preview\n'
Common mistake: Using cfg! to guard code that cannot type-check on the current target.
#[cfg_attr] — Apply attributes conditionally#[cfg_attr(predicate, attribute, ...)]
Conditionally attach one or more attributes. When the predicate is false, the listed attributes are not added; the item itself is not automatically removed. Useful for optional derives or documentation attributes.
Result: Conditional attribute application.
Compiler flags: --cfg bytemind_debug.
Expected output (not executed): 'Ticket(7)\nID: 7\n'
Common mistake: Assuming cfg_attr by itself removes the annotated struct.
macro
expression
204 responses and body policyResponse::builder().status(StatusCode::NO_CONTENT).body(())
A 204 response has no content. HEAD and 304 also have distinct content restrictions. The http crate models messages but is not a complete semantic validator; obey protocol rules when using a transport.
External crate example; constructs data in memory, does not send requests.
Expected stdout (not executed):
204 true
Common mistake: Trying to decode a JSON response body unconditionally after a successful status.
A bounded single-task driver for a self-waking futurepoll → Pending + notification → poll → Ready
A scheduler decides when to drive a task after a wake notification. This toy driver supports only synchronous self-notifications from a fixed future; its finite iteration cap and failure on missing notification deliberately exclude general external I/O, timers, fairness and multi-task scheduling.
Expected stdout (not executed):
3
Common mistake: Using this bounded demonstration as an executor for arbitrary futures.
A documented niche for optional referencesOption<&T>
A niche is a representation unavailable to a valid value of a type. For sized referents the standard library guarantees Option<&T> has the same size, alignment and function-call ABI as &T. Use Option constructors rather than fabricating references from bytes.
Expected stdout (not executed):
true true true
Common mistake: Assuming every Option<T> uses the same representation as T.
ABA: equality does not prove unchanged historycompare_exchange(expected, replacement, success, failure)
A value can change from A to B and back to A, allowing a later comparison to succeed despite an intervening change. This fixed sequence demonstrates ABA without pointer dereferences. Real lock-free reclamation needs a verified algorithm, not just a comparison.
Expected stdout (not executed):
true
Common mistake: Assuming successful compare_exchange proves no intervening change occurred.
Abort and await cancellationhandle.abort(); handle.await
Request cancellation of a task and then await termination. An already completed task can still return successfully; a permanently pending future in this example is guaranteed not to complete normally. Abort is not rollback of earlier side effects. Tokio is an external dependency; see the proposed Cargo manifest.
Expected stdout (not executed):
true
Common mistake: Assuming abort synchronously completes cleanup or undoes external work.
AbortHandle: separate cancellation capabilityhandle.abort_handle(); abort_handle.abort()
Give another component the ability to request task cancellation without transferring the ability to await its output. Retain the original join handle to observe termination. Tokio is an external dependency; see the proposed Cargo manifest.
Expected stdout (not executed):
true
Common mistake: Assuming dropping an AbortHandle cancels the task.
Accept a Unix-domain connection in a scratch directoryUnixListener::bind(path); UnixStream::connect(path); listener.accept()
A filesystem-named Unix socket allows local processes with suitable access to connect. Bind only inside a private scratch directory, never unlink an arbitrary existing path. The path persists after dropping the listener, so its owner should remove it. This fixture uses a single local connection; the runner supplies a temporary directory.
Expected stdout (not executed): local: z
Common mistake: Unlinking an existing socket in a shared directory or assuming a pathname authenticates a peer.
Run only in the isolated fixture runner, not a public code playground.
Accept borrowed text when ownership is unnecessaryfn label(text: &str) -> usize
An inspection function should not require an owned String when it only needs to read text. A string slice accepts both a string literal and a borrowed String. Returning the byte length here is intentional; it is not the number of characters. Choose a narrower input type when it captures the true requirements.
Expected result (NOT RUN): 4 3
still owned: book
Common mistake: Taking String by value and forcing a caller to move or clone data for read-only inspection.
Static Rust example; not a verified ByteMind executable assessment.
Accept iterable inputs without prescribing storagefn total(values: impl IntoIterator<Item = u32>) -> Option<u32>
An API that only needs to traverse values can accept IntoIterator rather than requiring Vec. The item type describes what the function consumes. Here try_fold and checked_add reject overflow instead of silently wrapping. The same function accepts arrays and vectors of owned u32 values; borrowed slices require copying their items or a different contract.
Expected result (NOT RUN): array: Some(5)
overflow: None
Common mistake: Requiring Vec when no random access or ownership of the collection is needed.
Static Rust example; not a verified ByteMind executable assessment.
Account for alignment when estimating a section layoutaligned = (offset + align - 1) & !(align - 1)
A linker may insert padding to meet a section or object alignment. The example uses small fixed offsets and a power-of-two alignment. A real general calculation must check overflow and validate alignment; inspect the actual link map instead of treating this estimate as measured firmware size.
Expected host stdout (not executed):
next: 16, padding: 3
Common mistake: Adding only the lengths of objects and ignoring padding or reserved memory.
AcqRel ordering for read-modify-writen.swap(value, Ordering::AcqRel)
AcqRel combines acquire behavior for the read portion and release behavior for the write portion. On a failed comparison there is no write, and the separately specified failure ordering governs the load.
Expected stdout (not executed):
1 2
Common mistake: Passing AcqRel to a pure load.
Adapt a legacy interface without owning the sourcestruct Adapter<'a>(&'a Legacy); impl Sensor for Adapter<'_>
An adapter translates between interfaces while preserving the original implementation. A borrowed adapter can expose a domain-specific contract without cloning the underlying resource. Here an integer sensor reports tenths of a degree; the adapter exposes degrees as f64. The conversion and lifetime are explicit.
Expected result (NOT RUN): 23.5 C
Common mistake: Changing the original interface globally or hiding a unit conversion.
Static Rust example; not a verified ByteMind executable assessment.
Adjacently tagged enums#[serde(tag = "kind", content = "data")]
Keep the variant discriminator and payload in separate sibling properties; useful when payloads differ in shape. Serde and serde_json are external crates; use the staged Cargo manifest.
Expected stdout (not executed):
Count 12
Common mistake: Assuming the payload is always a JSON object.
Adjust channel brightness without integer wraparoundchannel.saturating_add(amount)
For a simple encoded-channel brightness adjustment, add an unsigned increment and clamp at 255. This is not a physically correct exposure adjustment in linear light. In an RGBA image, preserve alpha unless changing transparency is intended.
Expected result (NOT RUN): [40, 230, 255]
Common mistake: Using wrapping addition or assuming encoded RGB values are proportional to light intensity.
Static Rust example; not a verified ByteMind executable assessment.
Advance simulated time explicitlytokio::time::advance(duration).await
Jump the paused Tokio clock forward. Advancing time is not a synchronization barrier for all timer-triggered work. This fixture checks the clock rather than assuming a background task completed. Tokio is an external dependency; see the proposed Cargo manifest.
Expected stdout (not executed):
4
Common mistake: Assuming every awakened task finishes before advance returns.
trait
Add — overload + for combine two item countsT: std::ops::Add<Rhs, Output = O>
Add supplies the + operator. The trait consumes its receivers by value unless their types are references. Addition need not return the left operand type; Output is an associated type. Here a generic function delegates to the trait method on small primitive operands.
Expected stdout (not executed):
11
Common mistake: Assuming + always preserves the input type.
Static Rust 2024 example; not a verified ByteMind executable assessment.
AddAssign — mutate a value with +=fn add_assign(&mut self, rhs: Rhs)
AddAssign defines +=, which modifies a mutable receiver and returns unit. It is a separate trait from the non-assignment operator. Add new stock to a counter. Addition may overflow. This local wrapper delegates the operation to u32.
Expected stdout (not executed):
8
Common mistake: Assuming implementing the matching binary trait automatically implements AddAssign, or expecting += to return the updated value.
Static Rust 2024 example; not a verified ByteMind executable assessment.
Showing 20 of 2418 entries