skip to content

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 pageshow

explore

questions

480 · 19 sections

In Rust, why does `let status = if healthy { 200 } else { "down" };` fail, and how does `if` produce a value?

level: juniorimportance: must knowfreq 70%
basics
~20 s

In 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.

open as a page

In Rust, how does `let result = loop { ... break outcome; };` yield a value, and why can't `while` or `for` do the same?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A 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.

open as a page

In Rust, how does shadowing with `let port: u16 = port.parse()?;` differ from reassigning a `let mut port` binding?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Shadowing 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.

open as a page

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?

level: juniorimportance: must knowfreq 80%
basics
~20 s

A 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.

open as a page

Why does rustc reject a Rust `fn parse_port(s: &str) -> u16` with E0308 when its last line ends in a semicolon?

level: middleimportance: must knowfreq 66%
basics
~20 s

A 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.

open as a page

In Rust, what does `let Config { host, port: listen_port, .. } = cfg;` bind, and where else can such patterns appear?

level: juniorimportance: must knowfreq 58%
basics
~20 s

The 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Option<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.

open as a page

In Rust, how can one PaymentEvent enum hold unit, tuple and struct variants carrying different data, and how do you read it?

level: juniorimportance: must knowfreq 75%
basics
~20 s

A 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.

open as a page

In Rust, why does a match over an OrderState enum that leaves out Cancelled fail with E0004, and what must every arm agree on?

level: juniorimportance: must knowfreq 80%
basics
~20 s

A 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

An 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.

open as a page

In Rust, why does `let first = &ids[0];` followed by `ids.push(4)` compile only when `first` is not used after the push?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Under 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.

open as a page

In Rust, why can you still use a `Vec2` after `let b = a;`, but not a `Sprite` that holds a `String`?

level: juniorimportance: must knowfreq 80%
basics
~20 s

A 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().

open as a page

In Rust, why does calling `conn.drop()` on a pooled connection guard fail to compile, and how do you release it early instead?

level: juniorimportance: must knowfreq 60%
basics
~10 s

rustc 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.

open as a page

In Rust, after `let staged = batch;` or `archive(batch)` with a `Vec<String>`, why is `batch` unusable, and how does ownership come back?

level: juniorimportance: must knowfreq 82%
basics
~20 s

A 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.

open as a page

Why can a Rust reference never be null or dangling, and how do you return a lookup that may find nothing?

level: juniorimportance: must knowfreq 60%
basics
~20 s

Safe 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.

open as a page

In Rust, why does a config lookup `fn pick(primary: &str, fallback: &str) -> &str` need a lifetime parameter, and what does `'a` promise?

level: juniorimportance: must knowfreq 80%
basics
~20 s

The 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.

open as a page

In Rust, what is lifetime elision, and why does `fn first_line(text: &str) -> &str` compile without writing any lifetime?

level: juniorimportance: must knowfreq 74%
basics
~20 s

Lifetime 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.

open as a page

In Rust, what does the type `&'static str` promise, and why does every string literal have that type?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A &'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.

open as a page

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?

level: middleimportance: must knowfreq 68%
basics
~20 s

rustc 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.

open as a page

What are Rust's three lifetime elision rules, and how does the `&self` rule decide what a method's returned reference borrows from?

level: middleimportance: must knowfreq 70%
basics
~20 s

Each 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.

open as a page

In Rust, why does a generic `max_reading<T>` function that compares readings with `>` fail to compile until `T` gets a bound?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Rust 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.

open as a page

In Rust, how does a trait give a method a default body, and what happens when an implementing type overrides it?

level: juniorimportance: must knowfreq 78%
basics
~20 s

A 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.

open as a page

In Rust, why return `impl Iterator<Item = &i32>` from a function that filters a borrowed slice, and what may the caller do with it?

level: juniorimportance: must knowfreq 62%
basics
~20 s

The 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.

open as a page

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`?

level: juniorimportance: must knowfreq 76%
basics
~20 s

A 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.

open as a page

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?

level: middleimportance: must knowfreq 68%
basics
~20 s

With 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.

open as a page

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?

level: juniorimportance: must knowfreq 65%
basics
~20 s

Rust 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.

open as a page

In Rust, after you write `impl From<Celsius> for Fahrenheit`, why does `let f: Fahrenheit = c.into();` also compile?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Core 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.

open as a page

What does #[derive(Default)] generate for a Rust struct, and when does rustc refuse to compile it?

level: juniorimportance: must knowfreq 65%
basics
~20 s

It 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.

open as a page

In Rust, why can a `Money` struct use `#[derive(Debug)]` while its `Display` implementation must be written by hand?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Debug 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.

open as a page

In Rust, why can't a struct with f64 coordinate fields derive Eq, Ord or Hash, and how do you sort or key it?

level: middleimportance: must knowfreq 70%
basics
~20 s

Because 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.

open as a page

In a Rust tool using anyhow, how do you make an io::Error from fs::read_to_string say which manifest file failed?

level: juniorimportance: must knowfreq 60%
basics
~10 s

Import 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.

open as a page

In a Rust payment library, why return Result<T, PaymentError> with an error enum instead of Result<T, String>?

level: juniorimportance: must knowfreq 68%
basics
~20 s

An 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.

open as a page

In Rust, when should a function return Option<T> and when should it return Result<T, E>?

level: juniorimportance: must knowfreq 78%
basics
~20 s

Return 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.

open as a page

In Rust, when should code panic instead of returning a Result, and why does indexing a Vec out of bounds panic?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Panic 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.

open as a page

In Rust, what does the `?` operator do when applied to a `Result`, and how is that different from calling `unwrap`?

level: juniorimportance: must knowfreq 82%
basics
~20 s

On 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.

open as a page

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?

level: juniorimportance: must knowfreq 60%
basics
~20 s

BTreeMap 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.

open as a page

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?

level: juniorimportance: must knowfreq 62%
basics
~10 s

Use 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.

open as a page

In a Rust session cache `HashMap<String, u32>`, what do `insert`, `get` and `map[key]` return when a key is new, present or missing?

level: juniorimportance: must knowfreq 72%
basics
~20 s

insert 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.

open as a page

In Rust, why does `let first = name[0];` fail to compile when `name` is a `String`, and how do you get its first character?

level: juniorimportance: must knowfreq 75%
basics
~20 s

A 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.

open as a page

In Rust, when should a value be a fixed `[f32; 3]` array rather than a `Vec<f32>`, and what does each one cost?

level: juniorimportance: must knowfreq 72%
basics
~20 s

A [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.

open as a page

In Rust, how does a closure without `move` decide whether to capture each variable by shared borrow, mutable borrow or by value?

level: juniorimportance: must knowfreq 74%
basics
~20 s

A 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.

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Implement 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.

open as a page

In Rust, how do `Fn`, `FnMut` and `FnOnce` differ, and how does the compiler decide which of them a closure implements?

level: juniorimportance: must knowfreq 75%
basics
~20 s

Fn 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.

open as a page

In Rust, why is a `Vec<Task>` unusable after `for task in tasks { ... }`, and how do you loop without giving it up?

level: juniorimportance: must knowfreq 82%
basics
~20 s

A 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.

open as a page

In Rust, why does `lines.iter().map(parse)` on its own run no code, and what makes the chain actually execute?

level: juniorimportance: must knowfreq 80%
basics
~20 s

An 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.

open as a page

In Rust, why does `enum Expr { Num(i64), Add(Expr, Expr) }` fail with E0072, and how does `Box` fix it?

level: juniorimportance: must knowfreq 75%
basics
~20 s

rustc 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.

open as a page

In Rust, when do you use `Cell<T>` rather than `RefCell<T>` for state that a `&self` method must change?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Cell<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.

open as a page

In Rust, what does `Rc::clone(&config)` do to an `Rc<String>`, and when is the `String` itself dropped?

level: juniorimportance: must knowfreq 74%
basics
~20 s

Rc::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.

open as a page

In Rust, why model shared bank accounts as `Rc<RefCell<Account>>`, and what does each of the two layers contribute?

level: middleimportance: must knowfreq 70%
basics
~20 s

Rc<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.

open as a page

With Rust's `RefCell`, why does a method that calls `borrow_mut()` while iterating over `borrow()` compile, yet panic at run time?

level: middleimportance: must knowfreq 74%
basics
~20 s

RefCell 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.

open as a page

In Rust's std::sync::mpsc, what happens to a value when a thread sends it, and how does another thread receive it?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Sender::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.

open as a page

In Rust, why do request threads sharing a rate limiter's `HashMap` need `Arc<Mutex<HashMap<String, u32>>>` instead of a plain `Arc<HashMap<String, u32>>`?

level: juniorimportance: must knowfreq 80%
basics
~10 s

Arc only shares ownership: every thread gets a &HashMap, so insert fails with E0596. Mutex adds exclusive access: lock() turns &Mutex into a MutexGuard that derefs mutably and unlocks when dropped.

open as a page

In Rust, what do the `Send` and `Sync` marker traits each promise, and who implements them for your own structs?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Send 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.

open as a page

In Rust, what does `std::thread::spawn` return, and what happens to the spawned thread if `main` returns without joining it?

level: juniorimportance: must knowfreq 80%
basics
~20 s

thread::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.

open as a page

In Rust, why is `Ordering::Relaxed` enough for a shared `AtomicUsize` request counter, and is the total read after `join` exact?

level: middleimportance: must knowfreq 55%
basics
~20 s

Relaxed 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.

open as a page

In Rust, what does calling `async fn checksum(data: &[u8]) -> u32` give the caller, and what does that value capture?

level: juniorimportance: must knowfreq 74%
basics
~20 s

A 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.

open as a page

In Rust, a sensor gateway calls an async fn that sends a reading but forgets the .await; what happens, and why?

level: juniorimportance: must knowfreq 80%
basics
~20 s

Nothing 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.

open as a page

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`?

level: juniorimportance: must knowfreq 70%
basics
~20 s

Rust'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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

A 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.

open as a page

In Rust, what changes when you pass two futures to `futures::join!` instead of awaiting them one after the other?

level: juniorimportance: must knowfreq 72%
basics
~20 s

Sequential 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.

open as a page

In Rust 2024, how do you declare and call a C function such as `strlen`, and why does the call need `unsafe`?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Declare 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.

open as a page

In Rust, what can code inside an `unsafe` block do that safe code cannot, and which compiler checks keep running inside it?

level: juniorimportance: must knowfreq 78%
basics
~20 s

An 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.

open as a page

In Rust, what does it mean for a safe function that wraps `unsafe` code to be sound, and how is that different from correct?

level: middleimportance: must knowfreq 55%
basics
~20 s

A 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.

open as a page

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?

level: middleimportance: must knowfreq 55%
basics
~20 s

A 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.

open as a page

In Rust, why does `let p = &raw mut x;` compile in safe code while `*p += 1;` fails with E0133?

level: middleimportance: must knowfreq 62%
basics
~20 s

Creating 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.

open as a page

In Rust, how is the standard vec! macro defined with macro_rules!, and why does vec![value; n] need Clone?

level: juniorimportance: must knowfreq 60%
basics
~20 s

vec! 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.

open as a page

In Rust, how do you write a macro_rules! hashmap! literal macro that accepts key => value pairs with an optional trailing comma?

level: middleimportance: must knowfreq 50%
basics
~10 s

Match $($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.

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~20 s

Paths 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.

open as a page

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?

level: middleimportance: must knowfreq 45%
basics
~20 s

macro_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.

open as a page

In Rust, what does a custom derive such as #[derive(Builder)] do at compile time, and can it change the struct it annotates?

level: juniorimportance: should knowfreq 45%
basics
~20 s

A 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.

open as a page

In Rust, how do you write one function with separate Linux, macOS and Windows bodies using `#[cfg]`, and what happens to the unused ones?

level: juniorimportance: must knowfreq 58%
basics
~20 s

Write 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.

open as a page

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?

level: juniorimportance: must knowfreq 70%
basics
~20 s

rustc 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.

open as a page

In Rust, what do paths beginning with `crate::`, `self::` and `super::` resolve from, and when do you use each?

level: juniorimportance: must knowfreq 65%
basics
~20 s

crate:: 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.

open as a page

In Rust, what visibility do items and struct fields get by default, and what does marking them pub change?

level: juniorimportance: must knowfreq 76%
basics
~20 s

Every 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.

open as a page

How does `pub use` let a Rust library expose `geometry::Point` and a `geometry::prelude` when `Point` is defined deep inside a private module?

level: middleimportance: must knowfreq 55%
basics
~20 s

A 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.

open as a page

In Rust, how do you deserialize a JSON webhook body into an `OrderEvent` struct with Serde, and what does serde's `derive` feature add?

level: juniorimportance: must knowfreq 80%
basics
~10 s

Depend 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.

open as a page

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?

level: juniorimportance: must knowfreq 55%
basics
~20 s

The 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.

open as a page

In Rust with Serde, what do `rename_all = "camelCase"`, `default`, `skip_serializing_if` and `deny_unknown_fields` change for a webhook `OrderEvent` struct?

level: middleimportance: must knowfreq 70%
basics
~20 s

rename_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.

open as a page

In Rust, how does Serde write an `OrderEvent` enum to JSON by default, and what do `tag`, `content` and `untagged` change?

level: middleimportance: should knowfreq 60%
basics
~20 s

By 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.

open as a page

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`?

level: middleimportance: should knowfreq 45%
basics
~20 s

Each 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.

open as a page

In a Rust package, what does Cargo build from each file in the tests/ directory, and which library items can that code call?

level: juniorimportance: must knowfreq 55%
basics
~20 s

Cargo 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.

open as a page

In a Rust unit test, why does `assert_eq!(to_cents(135), Cents(14))` fail to compile until `Cents` derives `PartialEq` and `Debug`?

level: juniorimportance: must knowfreq 70%
basics
~10 s

assert_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.

open as a page

In Rust, what do `#[test]` and a `#[cfg(test)] mod tests` block do, and how do those tests reach a private helper function?

level: juniorimportance: must knowfreq 80%
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.

open as a page

In a Rust criterion benchmark, why does b.iter(|| { fnv1a(&buf); }) report about 225 picoseconds, and how does std::hint::black_box fix it?

level: middleimportance: must knowfreq 35%
basics
~20 s

The 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.

open as a page

A Rust doc example using ? fails cargo test with E0277; how does rustdoc wrap it, and how do hidden # lines fix it?

level: middleimportance: must knowfreq 45%
basics
~20 s

Rustdoc wraps an example lacking fn main in fn main() { ... }, which returns (), so ? cannot return an error. Add a hidden # fn main() -> Result<(), E> { with # Ok(()) and # }, or end with a hidden Ok::<(), E>(()).

open as a page

In embedded Rust, what do a peripheral access crate, a HAL crate, a board support crate and the embedded-hal traits each contribute?

level: juniorimportance: must knowfreq 34%
basics
~20 s

A 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.

open as a page

In Rust, what does `#![no_std]` take away from a crate, and what do the `core` and `alloc` crates still provide?

level: juniorimportance: must knowfreq 38%
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.

open as a page

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?

level: juniorimportance: must knowfreq 38%
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.

open as a page

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?

level: middleimportance: must knowfreq 40%
basics
~20 s

Make 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.

open as a page

In embedded Rust, why does `cortex_m::Peripherals::take()` return an `Option`, and what does the `unsafe` `steal()` give up?

level: middleimportance: must knowfreq 37%
basics
~20 s

Peripherals 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.

open as a page

In Rust, what are the stable, beta and nightly release channels, and how does a change travel from one to the next?

level: juniorimportance: must knowfreq 50%
basics
~20 s

Nightly 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.

open as a page

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?

level: middleimportance: must knowfreq 50%
basics
~20 s

Each 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.

open as a page

In Rust, what is an edition, how does a crate choose one, and why does 2015-edition code still compile on rustc 1.99?

level: juniorimportance: should knowfreq 48%
basics
~20 s

An 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.

open as a page

In Rust 2024, why do a 2021 crate's `extern "C"` block and `#[no_mangle]` function stop compiling, and what do the fixes promise?

level: middleimportance: should knowfreq 40%
basics
~20 s

Rust 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.

open as a page

When `cargo fix --edition` migrates a Rust 2018 crate toward 2021, what does it change, and what must you still fix by hand?

level: middleimportance: should knowfreq 38%
basics
~20 s

It 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.

open as a page