Rust
Rust buys memory safety without a garbage collector through ownership, borrowing and lifetimes, and its type system rules out data races too. Interviews test the rules behind both.
on this pageshowhide
explore
- Expressions and Scalars17 questions
- Blocks, Shadowing and Constants5 questions
- Integers, Floats and Casts6 questions
- Loops and Conditionals6 questions
- Structs, Enums and Patterns19 questions
- Methods and Receivers5 questions
- Variants with Payloads5 questions
- Match and Exhaustiveness5 questions
- Destructuring and Bindings4 questions
- Ownership and Borrowing31 questions
- Moves and Partial Moves5 questions
- Copy and Clone5 questions
- Drop and RAII5 questions
- References and Aliasing5 questions
- Slices and Borrowed Views5 questions
- Borrow Checker Errors6 questions
- Lifetimes29 questions
- Annotations in Signatures5 questions
- Elision Rules6 questions
- Structs Holding References5 questions
- Static Bounds4 questions
- Variance and Subtyping5 questions
- Higher-Ranked Bounds4 questions
- Traits and Generics36 questions
- Defining Shared Behaviour5 questions
- Bounds and Monomorphization6 questions
- Vtables and Dynamic Dispatch5 questions
- Associated Types4 questions
- Coherence and Orphan Rule4 questions
- Opaque Impl Types6 questions
- Const Parameters and Typestate6 questions
- Standard Library Traits26 questions
- From, Into and TryFrom6 questions
- Equality, Ordering and Hashing6 questions
- Display and Debug5 questions
- Operators and Deref5 questions
- Default and Constructors4 questions
- Errors and Panics32 questions
- Option and Result5 questions
- The Question Mark Operator5 questions
- Custom Failure Types6 questions
- Library vs Application Failures5 questions
- Unwinding and Aborting6 questions
- Context and Backtraces5 questions
- Owned Collection Types26 questions
- Vec and Arrays4 questions
- UTF-8 Strings and Slices6 questions
- HashMap and HashSet5 questions
- BTreeMap and BTreeSet6 questions
- VecDeque and BinaryHeap5 questions
- Iterators and Closures26 questions
- Lazy Adapters and Consumers5 questions
- Borrowing vs Consuming Iteration5 questions
- Captured Variables5 questions
- Fn, FnMut and FnOnce5 questions
- Custom Sequence Types6 questions
- Smart Pointers24 questions
- Box and Heap Allocation4 questions
- Rc and Weak4 questions
- Cell and RefCell5 questions
- Cow and Clone-on-Write5 questions
- OnceCell and LazyLock6 questions
- OS Threads and Locks32 questions
- Spawning and Scopes5 questions
- Send and Sync5 questions
- Mutex, RwLock and Arc6 questions
- Message-Passing Channels5 questions
- Atomics and Memory Ordering6 questions
- Rayon Parallel Iterators5 questions
- Asynchronous Programming40 questions
- Futures and Polling5 questions
- Async Functions and Blocks5 questions
- Pin and Unpin5 questions
- Send Futures and Spawning5 questions
- Awaitable Trait Methods5 questions
- Cancellation and Drop5 questions
- Runtimes and Blocking5 questions
- Streams and Concurrent Futures5 questions
- Unsafe Code and FFI27 questions
- Raw Pointers and Superpowers5 questions
- Undefined Behaviour and Miri5 questions
- Foreign Function Calls6 questions
- Type Layout and Representation5 questions
- Sound Safe Abstractions6 questions
- Compile-Time Code Generation22 questions
- Declarative Macros6 questions
- Macro Hygiene and Scope6 questions
- Custom Derive Macros5 questions
- Attribute and Function-Like Macros5 questions
- Modules and Crates25 questions
- Source File Layout4 questions
- Paths and Imports5 questions
- Visibility and Privacy5 questions
- Conditional Compilation5 questions
- API Evolution and SemVer6 questions
- Common Library Crates10 questions
- Serde Data Model5 questions
- Logging and Tracing5 questions
- Verification and Benchmarking19 questions
- In-Module Unit Tests4 questions
- Integration Crates and Doctests5 questions
- Property Tests and Mocks5 questions
- Measuring Performance5 questions
- Embedded and WebAssembly23 questions
- Bare-Metal Crates6 questions
- Peripheral Access and HALs6 questions
- Interrupts and Shared State5 questions
- Browser and WASI Targets6 questions
- Compatibility over Time16 questions
- Per-Crate Editions5 questions
- The 2024 Edition6 questions
- Release Train and MSRV5 questions
questions
480 · 19 sectionsIn Rust, why does `let status = if healthy { 200 } else { "down" };` fail, and how does `if` produce a value?
basics
~20 sIn Rust, if is an expression: it evaluates to the value of the block that runs, so every arm must have the same type. An integer arm and a string-slice arm fail with E0308, if and else have incompatible types.
In Rust, how does `let result = loop { ... break outcome; };` yield a value, and why can't `while` or `for` do the same?
basics
~20 sA Rust loop evaluates to the operand of the break that ends it, so break outcome hands outcome to the let. A while or for loop can end without any break, so it always evaluates to (), and a valued break inside it is E0571.
In Rust, how does shadowing with `let port: u16 = port.parse()?;` differ from reassigning a `let mut port` binding?
basics
~20 sShadowing declares a brand-new variable that reuses the name, so port can go from &str to u16 and every binding stays immutable. Assigning to a let mut binding overwrites one variable, whose type never changes.
In Rust, what happens when a ledger's `u8` pending-transfer counter at 255 is incremented, in a debug build and in a release build?
basics
~20 sA debug build panics with "attempt to add with overflow"; a default release build silently wraps the counter to 0. Neither is undefined behaviour, and code that means to wrap or stop must say so explicitly.
Why does rustc reject a Rust `fn parse_port(s: &str) -> u16` with E0308 when its last line ends in a semicolon?
basics
~20 sA block's value is its final expression written without a semicolon. The semicolon turns that line into a statement, so the body has no final operand, evaluates to (), and fails with E0308 against the declared u16.
In Rust, what does `let Config { host, port: listen_port, .. } = cfg;` bind, and where else can such patterns appear?
basics
~20 sThe struct pattern binds host to the field of that name, binds the port field under the name listen_port, and .. ignores every other field. The same patterns work in function and closure parameters and in for loops.
In Rust, why is Option<T> an ordinary enum rather than a nullable value, and why can't an Option<u64> be passed where a u64 is expected?
basics
~20 sOption<T> is a plain library enum, enum Option<T> { None, Some(T) }, defined in core and imported by the prelude. Option<u64> is a different type from u64, so rustc rejects passing it (E0308) until code matches the value out.
In Rust, how can one PaymentEvent enum hold unit, tuple and struct variants carrying different data, and how do you read it?
basics
~20 sA Rust enum lists variants that may each carry their own fields: none (unit), positional (tuple) or named (struct). Every variant builds a value of the one enum type, and the fields are read only by matching the variant.
In Rust, why does a match over an OrderState enum that leaves out Cancelled fail with E0004, and what must every arm agree on?
basics
~20 sA Rust match must be exhaustive: rustc proves every value of the scrutinee's type is covered, so a missing OrderState::Cancelled arm is error E0004. Because match is an expression, every arm must also produce the same type.
In Rust, how does an associated function such as `Thermostat::new` differ from a method, and how do you declare and use an associated const?
basics
~20 sAn associated function has no self parameter, so it is called by path, Thermostat::new(18.5). A method has a self receiver and is called with a dot. An associated const sits in the impl block and is read as Self::MAX.
In Rust, why does `let first = &ids[0];` followed by `ids.push(4)` compile only when `first` is not used after the push?
basics
~20 sUnder non-lexical lifetimes a Rust borrow lasts until the reference's last use, not to the end of its block. If first is not read after ids.push(4), the shared borrow is already over; reading it later makes rustc reject the push with E0502.
In Rust, why can you still use a `Vec2` after `let b = a;`, but not a `Sprite` that holds a `String`?
basics
~20 sA Vec2 of two f32 fields implements Copy, so let b = a duplicates its bits and a stays valid. A Sprite owns a String, so it is not Copy: the same line moves it, and a duplicate needs an explicit clone().
In Rust, why does calling `conn.drop()` on a pooled connection guard fail to compile, and how do you release it early instead?
basics
~10 srustc rejects conn.drop() with E0040: Drop::drop only borrows the value, so it would stay usable and be dropped again at scope end. Call std::mem::drop(conn) instead; it takes ownership and runs the destructor once, immediately.
In Rust, after `let staged = batch;` or `archive(batch)` with a `Vec<String>`, why is `batch` unusable, and how does ownership come back?
basics
~20 sA Vec<String> is not Copy, so a let or a by-value call moves it: the new binding becomes the only owner and the old one is deinitialised, so any later use fails with E0382. Ownership comes back only as a return value.
Why can a Rust reference never be null or dangling, and how do you return a lookup that may find nothing?
basics
~20 sSafe Rust has no way to write a null reference, and rustc rejects any borrow used after its referent is dropped (E0597). A lookup that may find nothing returns Option<&T>, which std guarantees is the same size as &T.
In Rust, why does a config lookup `fn pick(primary: &str, fallback: &str) -> &str` need a lifetime parameter, and what does `'a` promise?
basics
~20 sThe returned &str may borrow from either argument, and the bare signature does not say which, so rustc stops with E0106. Writing 'a on both inputs and the output promises the result is valid only while both borrows are.
In Rust, what is lifetime elision, and why does `fn first_line(text: &str) -> &str` compile without writing any lifetime?
basics
~20 sLifetime elision is rustc filling in the lifetimes a function signature leaves out, by fixed rules. With exactly one input lifetime, the returned reference gets it, so first_line reads as fn first_line<'a>(text: &'a str) -> &'a str.
In Rust, what does the type `&'static str` promise, and why does every string literal have that type?
basics
~20 sA &'static str borrows string data that stays valid until the program ends. Literal bytes are compiled into the binary and never freed, so every literal has that type; a borrow of a local String never does.
In Rust, with `pick<'a>` tying both `&str` inputs to its result, why does E0597 appear when one input's `String` drops before the result is used?
basics
~20 srustc picks 'a as the region where both borrows are valid, so the result cannot outlive the shorter-lived String. Using it after that String drops breaks the contract, and rustc reports E0597 against that argument at the call.
What are Rust's three lifetime elision rules, and how does the `&self` rule decide what a method's returned reference borrows from?
basics
~20 sEach elided input lifetime becomes its own parameter; if there is exactly one input lifetime, every elided output gets it; in a method taking &self or &mut self, elided outputs get the receiver's lifetime. Any other elided output is error E0106.
In Rust, why does a generic `max_reading<T>` function that compares readings with `>` fail to compile until `T` gets a bound?
basics
~20 sRust type-checks a generic body once, against its bounds alone. An unbounded T promises no comparison, so r > best fails with E0369; adding T: PartialOrd permits it, and callers whose type lacks PartialOrd get E0277.
In Rust, how does a trait give a method a default body, and what happens when an implementing type overrides it?
basics
~20 sA trait method written with a body is a default: implementors inherit it unless their impl defines the same method, which replaces it completely. Defaults may call required methods; an override cannot call the default it replaced.
In Rust, why return `impl Iterator<Item = &i32>` from a function that filters a borrowed slice, and what may the caller do with it?
basics
~20 sThe real type is a Filter adapter holding a closure, whose type cannot be written. Returning impl Iterator hands it back unboxed and lazy; the caller sees an opaque type and may use only Iterator's methods.
In a Rust drawing app, why must a canvas holding circles and rectangles together be a `Vec<Box<dyn Shape>>` rather than a `Vec<T>` with `T: Shape`?
basics
~20 sA Vec has one element type and a generic T: Shape is one concrete type, so circles and rectangles cannot share a Vec<T>. Box<dyn Shape> erases each concrete type behind a pointer and a vtable, giving every element one type.
In Rust, why does the `Iterator` trait declare `type Item` instead of being generic as `Iterator<T>`, and when is a type parameter the better choice?
basics
~20 sWith an associated type, a type implements the trait at most once and the implementer fixes Item, so callers never annotate it. A type parameter allows one impl per argument type, which suits inputs such as Add's Rhs.
In Rust, why does `a == b` on two values of your own struct fail with E0369, and what do derive(PartialEq) and derive(Eq) add?
basics
~20 sRust has no automatic structural equality: == calls PartialEq::eq, so without an impl rustc reports E0369. derive(PartialEq) compares every field, plus the variant for enums; derive(Eq) adds no comparison logic, only the promise a == a, and needs every field Eq.
In Rust, after you write `impl From<Celsius> for Fahrenheit`, why does `let f: Fahrenheit = c.into();` also compile?
basics
~20 sCore has a blanket impl, Into<U> for T where U: From<T>, so implementing From<Celsius> for Fahrenheit gives Celsius an into() that calls Fahrenheit::from. The compiler only needs the target type, here from the let annotation.
What does #[derive(Default)] generate for a Rust struct, and when does rustc refuse to compile it?
basics
~20 sIt generates an impl Default whose default() calls Default::default() on every field, giving 0, false, empty strings and collections, and None. rustc rejects the derive with E0277 when any field's type does not implement Default.
In Rust, why can a `Money` struct use `#[derive(Debug)]` while its `Display` implementation must be written by hand?
basics
~20 sDebug is the developer view, which rustc can generate mechanically from the type name and every field. Display is the user-facing text, a design choice only the author can make, so std ships no derive for it.
In Rust, why can't a struct with f64 coordinate fields derive Eq, Ord or Hash, and how do you sort or key it?
basics
~20 sBecause NaN != NaN, f64 implements only PartialEq and PartialOrd, never Eq, Ord or Hash, so deriving them on a struct with f64 fields fails with E0277. Sort with sort_by(f64::total_cmp); key through a wrapper or an integer encoding.
In a Rust tool using anyhow, how do you make an io::Error from fs::read_to_string say which manifest file failed?
basics
~10 sImport anyhow::Context and call .with_context(|| format!("failed to load manifest {}", path.display())) on the Result. The Err becomes an anyhow::Error whose message names the file, with the original io::Error kept as its source.
In a Rust payment library, why return Result<T, PaymentError> with an error enum instead of Result<T, String>?
basics
~20 sAn error enum gives each failure a variant with its own data, so callers match on Declined, Network or InvalidCard instead of parsing text; rustc checks every variant is handled, and the enum can implement std::error::Error, which String does not.
In Rust, when should a function return Option<T> and when should it return Result<T, E>?
basics
~20 sReturn Option<T> when having no value is an ordinary outcome that needs no explanation, such as a map lookup; return Result<T, E> when the operation can fail and the caller needs to know why, such as parsing.
In Rust, when should code panic instead of returning a Result, and why does indexing a Vec out of bounds panic?
basics
~20 sPanic when a bug has broken an invariant; return Result when failure is expected, like bad input or a lost connection. An out-of-bounds Vec index panics because it breaks the caller's contract and reading past the buffer is never allowed.
In Rust, what does the `?` operator do when applied to a `Result`, and how is that different from calling `unwrap`?
basics
~20 sOn Ok(v), the ? operator evaluates to v; on Err(e), it returns Err(From::from(e)) from the enclosing function at once. unwrap panics on Err instead, so ? hands a recoverable failure to the caller rather than crashing.
In Rust, why does printing a BTreeMap<&str, usize> list keys in sorted order when a HashMap does not, and what must its key type implement?
basics
~20 sBTreeMap keeps entries sorted by key, so iteration and Debug output walk them in ascending order, and its key type must implement Ord. HashMap places entries by a randomly seeded hash, so its order is arbitrary, and it needs Hash + Eq instead.
In Rust, which std collection fits a sliding-window rate counter that appends new timestamps and expires old ones, and which methods do the work?
basics
~10 sUse std::collections::VecDeque: push_back each new timestamp, then pop_front while front() is older than the window. Both ends are amortised O(1), unlike Vec::remove(0), which shifts every remaining element.
In a Rust session cache `HashMap<String, u32>`, what do `insert`, `get` and `map[key]` return when a key is new, present or missing?
basics
~20 sinsert returns None for a new key and Some(old value) when it overwrites one; get returns Option<&V>, None when the key is missing; map[key] returns the value directly and panics with "no entry found for key" when it is absent.
In Rust, why does `let first = name[0];` fail to compile when `name` is a `String`, and how do you get its first character?
basics
~20 sA String holds UTF-8 bytes and a character takes one to four of them, so str can be indexed only by byte ranges. name[0] fails with E0277; name.chars().next() gives the first char, name.as_bytes()[0] the first byte.
In Rust, when should a value be a fixed `[f32; 3]` array rather than a `Vec<f32>`, and what does each one cost?
basics
~20 sA [f32; 3] stores exactly three floats inline, with the length fixed in its type and no allocation; a Vec<f32> is a pointer, capacity and length pointing at a heap buffer that can grow at run time.
In Rust, how does a closure without `move` decide whether to capture each variable by shared borrow, mutable borrow or by value?
basics
~20 sA Rust closure without move inspects what its body does with each outside variable: reading it takes a shared borrow, mutating it takes a mutable borrow, and moving it out captures it by value. rustc picks the weakest mode that works.
In Rust, what must you write to turn a struct generating a Fibonacci-like ID sequence into an iterator usable with for, map and take?
basics
~20 sImplement Iterator for the struct: declare type Item = u64 and write fn next(&mut self) -> Option<u64>, returning None when the sequence ends. Adapters such as map and take, and for loops, then work with no further code.
In Rust, how do `Fn`, `FnMut` and `FnOnce` differ, and how does the compiler decide which of them a closure implements?
basics
~20 sFn is called through &self, FnMut through &mut self and FnOnce by value. Every closure implements FnOnce; one that never moves a captured value out also implements FnMut, and one that also never mutates a capture implements Fn.
In Rust, why is a `Vec<Task>` unusable after `for task in tasks { ... }`, and how do you loop without giving it up?
basics
~20 sA Rust for loop calls IntoIterator::into_iter on its expression, and for a Vec<Task> passed by value that takes ownership, so the vector is moved and later use is E0382. Loop over &tasks or &mut tasks to borrow it instead.
In Rust, why does `lines.iter().map(parse)` on its own run no code, and what makes the chain actually execute?
basics
~20 sAn adapter such as map only wraps the source iterator and the closure in a new struct; no closure runs until a consumer such as collect, sum, count, for_each or a for loop calls next. rustc warns when the chain is dropped unused.
In Rust, why does `enum Expr { Num(i64), Add(Expr, Expr) }` fail with E0072, and how does `Box` fix it?
basics
~20 srustc needs every type's size at compile time, and an Expr holding two Exprs inline would be infinitely large. Boxing each child puts it on the heap behind a fixed-size pointer, so Expr gets a finite size.
In Rust, when do you use `Cell<T>` rather than `RefCell<T>` for state that a `&self` method must change?
basics
~20 sCell<T> fits small values replaced whole, like a hit counter: it moves values in and out and never lends a reference. RefCell<T> lends &T or &mut T through guards, for a map or Vec, checking borrows at run time and panicking on conflict.
In Rust, what does `Rc::clone(&config)` do to an `Rc<String>`, and when is the `String` itself dropped?
basics
~20 sRc::clone copies no String data: it adds one to the strong count and returns another pointer to the same heap allocation. Each Rc dropped subtracts one, and the String is dropped when the last strong Rc goes away.
In Rust, why model shared bank accounts as `Rc<RefCell<Account>>`, and what does each of the two layers contribute?
basics
~20 sRc<T> gives one value several owners but only lends &T, so assigning through it fails with E0594. RefCell<T> adds mutation through that &T, checked at run time. Together they give many handles, each able to borrow_mut the account, on one thread.
With Rust's `RefCell`, why does a method that calls `borrow_mut()` while iterating over `borrow()` compile, yet panic at run time?
basics
~20 sRefCell moves the borrow rules to run time. The Ref from borrow() stays alive for the whole for loop, so borrow_mut() inside it finds a live shared borrow and panics with "RefCell already borrowed". Shorten the shared borrow, or use try_borrow_mut.
In Rust's std::sync::mpsc, what happens to a value when a thread sends it, and how does another thread receive it?
basics
~20 sSender::send takes the value by value, so ownership moves into the channel and any later use is error E0382. The receiving thread calls recv, which blocks until a message arrives, or loops with for msg in rx.
In Rust, what do the `Send` and `Sync` marker traits each promise, and who implements them for your own structs?
basics
~20 sSend means a value may be moved to another thread; Sync means &T may be shared across threads, so T: Sync exactly when &T: Send. Both are auto traits that rustc implements for a struct whose fields all implement them.
In Rust, what does `std::thread::spawn` return, and what happens to the spawned thread if `main` returns without joining it?
basics
~20 sthread::spawn returns a JoinHandle<T> for the closure's result; join() waits and gives Ok(T) or an Err carrying the panic payload. Dropping the handle detaches the thread, and once main returns the process exits, stopping any thread still running.
In Rust, why is `Ordering::Relaxed` enough for a shared `AtomicUsize` request counter, and is the total read after `join` exact?
basics
~20 sRelaxed still makes each fetch_add one indivisible read-modify-write, so no increment is lost; it only drops ordering with other memory. JoinHandle::join makes every thread operation happen-before it returns, so the total read after joining is exact.
In Rust, what does calling `async fn checksum(data: &[u8]) -> u32` give the caller, and what does that value capture?
basics
~20 sA call returns a value of an anonymous compiler-generated type implementing Future with Output = u32, not a u32. That future owns the function's arguments, including the borrowed slice, and runs the body only when it is polled.
In Rust, a sensor gateway calls an async fn that sends a reading but forgets the .await; what happens, and why?
basics
~20 sNothing is sent. Calling an async fn only builds a future; its body runs when that future is polled, normally through .await. The unawaited future is dropped at the end of the statement, and rustc warns through unused_must_use.
Rust's standard library defines `Future` and `async`/`.await` but no runtime, so how does a Rust program actually run an async function from `main`?
basics
~20 sRust's std ships the Future trait and async syntax but no executor, and rustc rejects async fn main (E0752). A synchronous main passes the top-level future to an executor's block_on, such as futures::executor::block_on or smol::block_on.
In Rust, why does a multi-threaded executor's spawn function demand a future that is both `Send` and `'static`, and how does `async move` help?
basics
~20 sA spawned future may be resumed on any worker thread and may outlive the function that spawned it, so the spawn function requires Send and 'static. An async move block owns the variables it captures instead of borrowing them.
In Rust, what changes when you pass two futures to `futures::join!` instead of awaiting them one after the other?
basics
~20 sSequential awaits run the futures one after the other, so the waits add up. futures::join! polls both on one task, interleaving them at each .await, so the total is about the longest wait: concurrency, not parallelism.
In Rust 2024, how do you declare and call a C function such as `strlen`, and why does the call need `unsafe`?
basics
~20 sDeclare the C signature inside an unsafe extern "C" block and call it inside an unsafe block: rustc cannot check foreign code, so the caller vouches for its preconditions. An item declared safe fn needs no unsafe block.
In Rust, what can code inside an `unsafe` block do that safe code cannot, and which compiler checks keep running inside it?
basics
~20 sAn unsafe block unlocks a few operations: dereferencing raw pointers, calling unsafe functions, using a static mut and reading union fields, while unsafe impl covers unsafe traits. Borrow checking, type checking and bounds checks all stay on.
In Rust, what does it mean for a safe function that wraps `unsafe` code to be sound, and how is that different from correct?
basics
~20 sA safe function is sound when no input or call sequence available to safe code can make it cause undefined behaviour. Correctness means returning the right result; a sound function may still be buggy, but its bugs stay defined.
In Rust, why is `Option<&u64>` the same size as `&u64` while `Option<u32>` is twice the size of `u32`, and which sizes are guaranteed?
basics
~20 sA reference is never null, so rustc encodes None as the null pointer and Option<&u64> stays 8 bytes. Every u32 bit pattern is valid, so Option<u32> needs a separate tag. Only a documented list of types gets this guarantee.
In Rust, why does `let p = &raw mut x;` compile in safe code while `*p += 1;` fails with E0133?
basics
~20 sCreating a raw pointer is harmless: it is only an address and may be null, dangling or aliased. Dereferencing it can touch invalid memory, so only the dereference, and pointer methods such as add or read, need an unsafe block.
In Rust, how is the standard vec! macro defined with macro_rules!, and why does vec![value; n] need Clone?
basics
~20 svec! is a macro_rules! macro with three arms tried in order: empty, element-semicolon-count, and a comma-separated list of expressions. The repeat arm calls vec::from_elem, which fills the vector by cloning the element, so vec![x; n] needs x: Clone.
In Rust, how do you write a macro_rules! hashmap! literal macro that accepts key => value pairs with an optional trailing comma?
basics
~10 sMatch $($key:expr => $value:expr),* $(,)? and transcribe a block that creates a HashMap, repeats map.insert($key, $value); once per pair, and returns the map. The inner braces make the expansion one block expression.
A Rust utility crate exports `log_once!`, which calls the crate's own helper function; why must the macro write `$crate::` instead of `crate::` or a bare name?
basics
~20 sPaths in a macro_rules! body resolve where the macro is invoked, so a bare helper name or crate:: points into the caller's crate and fails with E0425. $crate always means the defining crate, though the helper must still be pub.
In Rust, why can code after a `macro_rules!` call not read a variable the expansion declared with `let`, and how do you hand one out?
basics
~20 smacro_rules! hygiene resolves local variables and labels where the macro was defined, so a let inside an expansion is invisible to the caller (E0425) and never captures the caller's variables. To hand one out, take its name as a $name:ident fragment.
In Rust, what does a custom derive such as #[derive(Builder)] do at compile time, and can it change the struct it annotates?
basics
~20 sA custom derive is a function in a proc-macro crate that rustc runs while compiling: it receives the struct's tokens and returns new items, which rustc appends after the struct. It cannot edit or remove the struct itself.
In Rust, how do you write one function with separate Linux, macOS and Windows bodies using `#[cfg]`, and what happens to the unused ones?
basics
~20 sWrite one copy of the function per platform, each gated by a cfg predicate such as target_os = "linux" or windows, plus a not(any(...)) fallback. rustc deletes every copy whose predicate is false before it resolves names or checks types.
In Rust, a CLI's main.rs says mod config; — where does rustc look for its code, and why is an undeclared src/storage.rs ignored?
basics
~20 srustc loads mod config; from src/config.rs or src/config/mod.rs and makes it crate::config. It starts at the crate root and follows mod declarations, so a file that no mod (or include! call) names is never parsed or compiled.
In Rust, what do paths beginning with `crate::`, `self::` and `super::` resolve from, and when do you use each?
basics
~20 scrate:: starts at the crate root, self:: at the current module and super:: at its parent. Use crate:: for distant items, super:: for a parent or sibling, and self:: only to stress that a name is local.
In Rust, what visibility do items and struct fields get by default, and what does marking them pub change?
basics
~20 sEvery Rust item and struct field is private to its defining module and that module's descendants unless marked pub. Marking a struct pub leaves its fields private; only enum variants and pub trait items inherit their parent's visibility.
How does `pub use` let a Rust library expose `geometry::Point` and a `geometry::prelude` when `Point` is defined deep inside a private module?
basics
~20 sA pub use at the crate root, such as pub use shapes::point::Point, publishes the item as geometry::Point while it stays defined in a private module. A pub mod prelude of re-exports gives users one glob import.
In Rust, how do you deserialize a JSON webhook body into an `OrderEvent` struct with Serde, and what does serde's `derive` feature add?
basics
~10 sDepend on serde with its derive feature plus serde_json, put #[derive(Serialize, Deserialize)] on OrderEvent, and call serde_json::from_str, which returns Result<OrderEvent, serde_json::Error>. Without that feature the derive macros do not exist.
In Rust, why does a background job's `log::info!` print nothing until `env_logger::init()` runs, and how does `RUST_LOG` decide what appears?
basics
~20 sThe log crate is only a facade: until the binary installs a logger, every macro call goes to a built-in no-op logger and is dropped. env_logger::init() installs one that writes to stderr and filters by RUST_LOG, showing only errors when it is unset.
In Rust with Serde, what do `rename_all = "camelCase"`, `default`, `skip_serializing_if` and `deny_unknown_fields` change for a webhook `OrderEvent` struct?
basics
~20 srename_all maps snake_case fields to camelCase keys, default fills an absent field from Default, skip_serializing_if omits a field on output when its predicate is true, and deny_unknown_fields turns unexpected keys into errors instead of ignoring them.
In Rust, how does Serde write an `OrderEvent` enum to JSON by default, and what do `tag`, `content` and `untagged` change?
basics
~20 sBy default Serde externally tags an enum: {"Paid": {...}}. #[serde(tag = "type")] puts the variant name inside the object, content = "data" nests the fields beside the tag, and untagged writes only the fields, trying each variant in order.
In Rust's tracing crate, what does `#[instrument(skip(db), fields(order_id = %id))]` on `async fn charge(db: &Db, id: OrderId, amount_cents: u64)` record, and why skip `db`?
basics
~20 sEach call gets an INFO span named charge, entered while the future runs. Arguments become fields (id with Debug, amount_cents as a number) plus order_id via Display. skip(db) leaves out db, whose type has no Debug impl, which would otherwise fail with E0277.
In a Rust package, what does Cargo build from each file in the tests/ directory, and which library items can that code call?
basics
~20 sCargo compiles each top-level .rs file in tests/ as its own crate and test executable, linked against the package's library. That code can call only the library's public API, exactly as a downstream crate would.
In a Rust unit test, why does `assert_eq!(to_cents(135), Cents(14))` fail to compile until `Cents` derives `PartialEq` and `Debug`?
basics
~10 sassert_eq! compares its arguments with ==, which needs PartialEq, and on failure prints both with {:?}, which needs Debug. A bare struct has neither, so rustc reports E0369 and E0277; #[derive(PartialEq, Debug)] fixes both.
In Rust, what do `#[test]` and a `#[cfg(test)] mod tests` block do, and how do those tests reach a private helper function?
basics
~20 s#[test] marks a no-argument function for the test harness; #[cfg(test)] compiles the tests module only in test builds. A child module may use its ancestors' private items, so use super::* lets tests call private helpers.
In a Rust criterion benchmark, why does b.iter(|| { fnv1a(&buf); }) report about 225 picoseconds, and how does std::hint::black_box fix it?
basics
~20 sThe closure throws away fnv1a's result, so the optimiser deletes the pure call and criterion times an empty loop. Return the value, which Bencher::iter passes to black_box, and wrap inputs in std::hint::black_box so they stay opaque.
In embedded Rust, what do a peripheral access crate, a HAL crate, a board support crate and the embedded-hal traits each contribute?
basics
~20 sA peripheral access crate, generated from the chip's SVD file by svd2rust, exposes typed registers; a HAL crate wraps them in safe types implementing embedded-hal traits; a board support crate pre-wires one board; drivers need only the traits.
In Rust, what does `#![no_std]` take away from a crate, and what do the `core` and `alloc` crates still provide?
basics
~20 s#![no_std] stops std being linked and gives every module the core prelude. core keeps primitives, Option, Result, slices, iterators, fmt and atomics; alloc, added with extern crate alloc, brings Vec, String and Box; I/O, threads and HashMap stay in std.
In Rust, what does `#[wasm_bindgen]` generate for an exported function, and why can a browser not load the `.wasm` that `cargo build` produces directly?
basics
~20 s#[wasm_bindgen] wraps the function in an exported shim with a numeric signature (pointers and lengths), plus descriptor functions. The wasm-bindgen CLI, usually run by wasm-pack build, reads them, rewrites the module and writes the JavaScript glue a page imports.
In embedded Rust, how do you write a temperature-sensor driver once against embedded-hal 1.0's `I2c` trait so it runs on two different microcontrollers?
basics
~20 sMake the driver generic over a type parameter bounded by embedded_hal::i2c::I2c, store the bus by value, and return I2C::Error from its methods. Each chip's HAL implements I2c for its controller, so both firmwares pass their own bus in.
In embedded Rust, why does `cortex_m::Peripherals::take()` return an `Option`, and what does the `unsafe` `steal()` give up?
basics
~20 sPeripherals are singletons: the first take() returns Some and every later call returns None, so each piece of hardware has one owner. The unsafe steal() skips that check, making exclusive access your promise instead of the compiler's.
In Rust, what are the stable, beta and nightly release channels, and how does a change travel from one to the next?
basics
~20 sNightly is built every night from Rust's main branch. Every six weeks beta forks from it, and the previous beta ships as the next stable release. Unstable features work only on nightly, behind #![feature] gates.
In Rust, why can a 2018-edition crate depend on 2021- and 2024-edition crates in one build, and what may an edition not change?
basics
~20 sEach crate is compiled with its own edition, and every edition lowers to the same internal representation, so the compiled crates link normally. An edition may change keywords, syntax, lints and the prelude, but not std's types and trait impls.
In Rust, what is an edition, how does a crate choose one, and why does 2015-edition code still compile on rustc 1.99?
basics
~20 sAn edition is a language mode chosen per crate (2015, 2018, 2021 or 2024). Changes that would break old code, such as new keywords, land only in a new edition, so a crate keeps compiling until it opts in.
In Rust 2024, why do a 2021 crate's `extern "C"` block and `#[no_mangle]` function stop compiling, and what do the fixes promise?
basics
~20 sRust 2024 requires unsafe extern blocks and writes no_mangle, export_name and link_section as #[unsafe(...)]. Each unsafe marks a promise rustc cannot check: the declared signatures match the foreign code, and the exported symbol collides with nothing.
When `cargo fix --edition` migrates a Rust 2018 crate toward 2021, what does it change, and what must you still fix by hand?
basics
~20 sIt runs cargo check with the next edition's compatibility lints and applies their suggestions so the code compiles on both editions. It leaves the edition key, doctests, inactive cfg code, uninvoked macros and generated code to you.