Rust Interview Questions
Rust systems engineering guide: affine type system, borrow checker mechanics, lifetime elision, fearless concurrency, Send/Sync traits, and unsafe blocks.
Practice Rust Interview Questions
Showing 16 of 16 technical questions with engineering explanations
What are Rust's three ownership rules, and what is the difference between Move and Copy semantics?
Senior Engineering Answer
Rust's ownership rules are: (1) every value has a single owner, (2) there can only be one owner at a time, and (3) when the owner goes out of scope, the value is dropped via Drop::drop. Assigning or passing a non-Copy type (such as String or Vec<T>) moves ownership bitwise and invalidates the previous variable, preventing double-frees. Types implementing the Copy marker trait (such as integers, bool, char, and tuples of Copy types) are duplicated via shallow bitwise copy instead of moving, and a type cannot implement both Copy and Drop.
let s1 = String::from("hello");
let s2 = s1; // Ownership moves to s2; using s1 afterwards fails to compile
let x: i32 = 42;
let y = x; // i32 implements Copy; both x and y remain validThinking Move performs a deep heap copy: moving a String only copies the 24-byte stack header (ptr, len, cap) and invalidates the old binding—the heap buffer itself never moves.
How do borrowing rules (&T vs &mut T) and Non-Lexical Lifetimes (NLL) prevent data races at compile time?
Senior Engineering Answer
At any point in a program, a value may have either any number of shared immutable references (&T) OR a single exclusive mutable reference (&mut T), never both simultaneously, and references must never outlive the referent. This XOR aliasing rule eliminates iterator invalidation, use-after-free, and data races statically. Since Rust 2018, Non-Lexical Lifetimes (NLL) end a borrow at the last point the reference is actually used rather than at the closing curly brace, reducing false-positive borrow errors.
let mut data = vec![1, 2, 3];
let first = &data[0];
println!("first = {first}"); // Last use of immutable borrow `first`
data.push(4); // Valid under NLL because `first` is no longer liveAssuming &T guarantees the underlying memory can never change: if T uses interior mutability (like Cell or AtomicUsize), &T still allows mutation through controlled APIs.
What is the difference between String, &str, and Cow<'a, str>, and when should you choose each?
Senior Engineering Answer
String is an owned, heap-allocated, growable UTF-8 buffer (ptr, len, cap). &str is a borrowed string slice (a fat pointer containing ptr and len) referencing UTF-8 bytes stored on the stack, heap, or binary static data. Cow<'a, str> (Clone-on-Write) is an enum holding either Borrowed(&'a str) or Owned(String), allowing functions to return borrowed slices on the fast path and allocate a String only when modification or escaping is actually required.
use std::borrow::Cow;
fn normalize_whitespace(input: &str) -> Cow<'_, str> {
if input.contains('\t') {
Cow::Owned(input.replace('\t', " "))
} else {
Cow::Borrowed(input)
}
}Accepting &String as a function parameter instead of &str: &str accepts both &String (via Deref coercion) and string literals, whereas &String needlessly forces callers with literals to allocate.
How do Option<T>, Result<T, E>, and the ? operator replace nulls and exceptions in Rust?
Senior Engineering Answer
Rust has no null pointer or runtime exceptions for recoverable failures. Absence is encoded in the type system as Option<T> (Some(T) | None), and recoverable errors as Result<T, E> (Ok(T) | Err(E)). The ? operator short-circuits a function on None or Err(e), converting the error via From::from into the caller's error type. Combined with exhaustive match, callers cannot accidentally ignore a missing value or failure path.
use std::fs;
use std::io;
fn read_port(path: &str) -> Result<u16, Box<dyn std::error::Error>> {
let contents = fs::read_to_string(path)?;
let port: u16 = contents.trim().parse()?;
Ok(port)
}Overusing .unwrap() or .expect() in production request handlers: an unexpected None/Err panics and unwinds (or aborts) the task/thread.
How do Rust lifetimes ('a) and lifetime elision rules work, and when is 'static required?
Senior Engineering Answer
Lifetime parameters ('a) do not change how long a value lives; they describe the relationship between the scopes of references so the compiler can prove returned references remain valid. Rust elides lifetimes in common signatures using three rules: (1) each input reference gets its own lifetime, (2) if there is one input lifetime, it is assigned to all output references, and (3) if &self or &mut self is present, its lifetime is assigned to all outputs. 'static means a value contains no non-static borrowed references (so it can safely live for the remainder of the program), which is why spawned threads (std::thread::spawn, tokio::spawn) require T: 'static.
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
if x.len() >= y.len() { x } else { y }
}Misreading T: 'static as 'T must be a compile-time constant or leaked forever': an owned String satisfies String: 'static because it owns its heap data and borrows nothing, even though it can be dropped at any time.
Compare static dispatch (impl Trait / generics) vs dynamic dispatch (dyn Trait), including object safety.
Senior Engineering Answer
Generics and impl Trait use static dispatch via monomorphization: the compiler generates specialized machine code per concrete type, enabling inlining with zero runtime indirection at the cost of larger binaries and slower compile times. Trait objects (&dyn Trait or Box<dyn Trait>) use dynamic dispatch via a fat pointer consisting of a data pointer and a vtable pointer, allowing heterogeneous collections and smaller binaries. A trait is dyn-compatible (object safe) only if its methods do not return Self by value, have no generic type parameters, and take a receiver like &self.
trait Handler { fn handle(&self, req: &str); }
// Static dispatch (monomorphized)
fn run_static(h: &impl Handler, r: &str) { h.handle(r); }
// Dynamic dispatch (heterogeneous collection via vtable)
fn run_all(handlers: &[Box<dyn Handler>], r: &str) {
for h in handlers { h.handle(r); }
}Assuming Box<dyn Trait> is always slow or always necessary: dynamic dispatch costs a single pointer indirection, whereas excessive monomorphization of large generic functions can hurt instruction-cache locality.
Compare Rc<RefCell<T>>, Arc<Mutex<T>>, and Cell<T> for interior mutability.
Senior Engineering Answer
Interior mutability lets you mutate data behind a shared reference (&T) safely. Cell<T> gives zero-overhead get/set for Copy types (or replace/take) in single-threaded code without runtime panics. RefCell<T> enforces Rust's XOR borrowing rules dynamically at runtime (panicking on conflicting borrows) and pairs with Rc<T> for single-threaded shared graphs. For multi-threaded shared state, Arc<T> uses atomic reference counting and pairs with Mutex<T> or RwLock<T> (or lock-free atomics) to synchronize access across threads.
use std::sync::{Arc, Mutex};
let counter = Arc::new(Mutex::new(0_u64));
let clone = Arc::clone(&counter);
std::thread::spawn(move || {
let mut guard = clone.lock().unwrap();
*guard += 1;
});Holding a RefCell RefMut guard or std::sync::MutexGuard across an .await point in async Rust: RefCell is !Sync, and std::sync::MutexGuard blocks the OS worker thread while held across an await, risking deadlocks.
How should you structure error handling in Rust libraries vs applications (thiserror vs anyhow)?
Senior Engineering Answer
Libraries should expose structured, strongly typed error enums implementing std::error::Error so downstream callers can match on specific failure variants—thiserror derives Error, Display, and From conversions with zero boilerplate. Applications and services typically only need to attach context, log, and propagate failures to a top-level boundary (like an HTTP error mapper), making anyhow::Result<T> with .context(...) ergonomic while preserving the full causal chain and optional backtraces.
use thiserror::Error;
#[derive(Debug, Error)]
pub enum ConfigError {
#[error("I/O error reading config")]
Io(#[from] std::io::Error),
#[error("invalid port {0}")]
InvalidPort(u16),
}Returning anyhow::Error from a public library API: it forces callers into fragile string matching or downcasting instead of exhaustive pattern matching.
Explain the Send and Sync marker traits: what does each mean, and which standard types are !Send or !Sync?
Senior Engineering Answer
A type T is Send if ownership of T can be safely transferred across thread boundaries. A type T is Sync if &T can be safely shared across threads (formally, T is Sync if and only if &T is Send). Both are unsafe auto-traits derived automatically when all fields satisfy them. Rc<T> is !Send and !Sync (non-atomic refcount), Cell<T> and RefCell<T> are Send (if T: Send) but !Sync (unsynchronized interior mutation), MutexGuard<'a, T> is !Send (OS mutexes must unlock on the locking thread), and raw pointers *const T / *mut T are neither Send nor Sync.
// Compile-time assertion pattern to prevent accidental regressions
fn assert_send_sync<T: Send + Sync>() {}
// assert_send_sync::<std::rc::Rc<i32>>(); // Compile error!Manually writing unsafe impl Send for MyType or unsafe impl Sync for MyType just to satisfy tokio::spawn without guaranteeing thread-safe synchronization—this instantly introduces undefined behavior.
How does Rust's async/await compile to state machines, and why does Pin<&mut Self> exist?
Senior Engineering Answer
Rust uses stackless coroutines: every async fn compiles into an anonymous state machine enum implementing Future<Output = T>, storing local variables live across .await suspension points inside the enum itself. Because a local variable in state A might borrow another local variable inside the same future struct across an .await, the generated Future can be self-referential. If a self-referential struct were moved in memory (mem::swap), its internal pointer would dangle. Pin<P> wraps a pointer and prevents obtaining &mut T (moving the value out) unless T: Unpin, guaranteeing the future stays at a fixed memory address while polled.
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
fn poll_boxed(mut fut: Pin<Box<dyn Future<Output = ()> + Send>>, cx: &mut Context<'_>) -> Poll<()> {
fut.as_mut().poll(cx)
}Running CPU-heavy synchronous loops or blocking std::fs / std::thread::sleep inside an async Tokio task: because Futures are cooperative, failing to yield starves the Tokio worker thread and stalls all other tasks scheduled on it—use tokio::task::spawn_blocking.
How does Tokio's work-stealing multi-threaded executor work, and what happens when a Future is dropped before completion?
Senior Engineering Answer
Tokio runs one OS worker thread per core, each with a local LIFO slot + ring-buffer run queue and a global injection queue. When a future returns Poll::Pending, it registers the Context's Waker with an I/O reactor (mio/epoll/kqueue) or timer wheel; when ready, waker.wake() pushes the task back onto a queue, and idle workers steal tasks from busy workers. Crucially, Rust Futures are lazy and cancellation is implicit: dropping a Future (e.g., inside tokio::select! when another branch wins) immediately drops its state machine at its current await point without running cleanup code after that await.
tokio::select! {
res = fetch_primary() => handle(res),
_ = tokio::time::sleep(Duration::from_millis(50)) => {
// fetch_primary() future is dropped here; must be cancellation-safe!
}
}Using non-cancellation-safe futures inside tokio::select! loops (e.g., reading partial framed data into an internal buffer): dropping the future mid-operation silently discards already-read bytes.
What are Drop order rules, PhantomData, and the Drop Check (dropck) in Rust?
Senior Engineering Answer
Local variables are dropped in reverse order of declaration (LIFO), while struct fields are dropped in declaration order (top to bottom) after the struct's own Drop::drop(&mut self) runs. PhantomData<T> is a zero-sized marker telling the compiler that a type logically owns or borrows T (affecting variance, Send/Sync, and drop check), commonly used in FFI wrappers or custom smart pointers holding raw pointers *const T. Drop check ensures that if a generic type implements Drop, any borrowed references inside T outlive the container because Drop::drop could inspect them.
use std::marker::PhantomData;
struct SliceView<'a, T> {
ptr: *const T,
len: usize,
_marker: PhantomData<&'a T>, // Encodes shared borrow lifetime 'a and covariance
}Assuming Drop runs when a value is forgotten via std::mem::forget or leaks in an Rc reference cycle: Rust guarantees memory safety without guaranteeing that destructors always run (leak amplification).
What invariants must unsafe Rust uphold, and how do Stacked Borrows / Tree Borrows and Miri validate them?
Senior Engineering Answer
The unsafe keyword unlocks five superpowers (dereferencing raw pointers, calling unsafe functions/FFI, accessing mutable statics, implementing unsafe traits, accessing union fields) while all normal borrow-checker rules remain active. Crucially, unsafe code must never cause Undefined Behavior: no dangling/unaligned dereferences, no data races, no invalid enum/bool bit patterns, and crucially, no violation of LLVM noalias guarantees derived from &mut T exclusivity. Tools like Miri interpret MIR under Stacked Borrows / Tree Borrows aliasing models to catch subtle provenance and aliasing bugs before production.
// Sound MaybeUninit initialization avoids UB from uninitialized memory reads
use std::mem::MaybeUninit;
let mut buf: [MaybeUninit<u8>; 64] = [const { MaybeUninit::uninit() }; 64];
for (i, slot) in buf.iter_mut().enumerate() {
slot.write(i as u8);
}
// SAFETY: All 64 elements were initialized in the loop above.
let initialized: [u8; 64] = unsafe { std::mem::transmute(buf) };Creating a &mut T reference to uninitialized memory (even before writing to it) or casting *const T to &mut T: merely materializing an invalid reference or violating exclusivity is immediate UB in Rust.
Explain subtyping and variance (covariant, invariant, contravariant) in Rust lifetimes and generic types.
Senior Engineering Answer
In Rust, subtyping applies to lifetimes: 'static is a subtype of any 'a because a longer-lived reference can safely be used where a shorter one is expected. A type constructor F<T> is covariant over T if F<'static> can be used as F<'a> (e.g., &'a T, Box<T>, Vec<T>). It is invariant when mutation is possible (e.g., &'a mut T is invariant in T, and UnsafeCell<T> / Cell<T> are invariant in T) because shortening a mutable target's lifetime would let a caller store a short-lived reference into a long-lived container. Function pointers fn(T) -> U are contravariant in argument T and covariant in return U.
// Compile error due to invariance of &mut T:
// fn overwrite<'a>(target: &mut &'a str, val: &'a str) { *target = val; }
// Passing &mut &'static str where &mut &'short str is expected is rejected
// because overwrite could store a short-lived &str into a 'static slot.Struggling with lifetime errors on &'a mut Container<'a>: tying the outer mutable borrow lifetime to the inner lifetime makes the borrow invariant and pins the container as exclusively borrowed for its entire life.
How do Higher-Ranked Trait Bounds (for<'a>) work, and when do you need them in generic APIs?
Senior Engineering Answer
A standard lifetime parameter <'a> on a function is chosen by the caller and fixed for the entire call. A Higher-Ranked Trait Bound (HRTB), written for<'a> F: Fn(&'a str) -> &'a str, requires the closure or trait implementation to work for ANY lifetime 'a chosen inside the callee—such as when iterating and passing references to short-lived local buffers created inside the function body. Serde's DeserializeOwned (for<'de> Deserialize<'de>) is a classic HRTB ensuring a type can deserialize from any temporary buffer lifetime.
fn apply_to_local<F>(f: F) -> usize
where
F: for<'a> Fn(&'a str) -> &'a str,
{
let local = String::from("hello world");
f(&local).len()
}Writing fn apply<'a, F: Fn(&'a str) -> &'a str>(f: F) when the string is created inside apply: the caller picks 'a to outlive apply's stack frame, making it impossible to pass &local.
How do you design zero-copy FFI boundaries and minimize binary bloat in large Rust workspaces?
Senior Engineering Answer
Across C FFI boundaries, mark structs #[repr(C)], validate non-null pointers, catch panics with std::panic::catch_unwind (unwinding across FFI is UB), and pass borrowed byte slices as (*const u8, usize) pairs rather than copying into C strings when binary protocols permit. To prevent binary bloat and slow incremental builds in large workspaces, split generic hot paths into thin generic wrappers delegating to non-generic inner functions (polymorphization/outlining), avoid unnecessary proc-macro expansion in leaf crates, and check symbol sizes with cargo-bloat.
#[no_mangle]
pub unsafe extern "C" fn parse_frame(ptr: *const u8, len: usize) -> i32 {
if ptr.is_null() { return -1; }
let res = std::panic::catch_unwind(|| {
let slice = unsafe { std::slice::from_raw_parts(ptr, len) };
process_slice(slice)
});
res.unwrap_or(-2)
}Allowing a Rust panic to unwind across an extern "C" function boundary or freeing memory allocated by C's malloc using Rust's Box::from_raw (which uses the Rust allocator, causing heap corruption).
Rust Track Coverage & Difficulty Profile
16 of 16 prompts include code examplesThis Rust preparation set groups 16 prompts across Junior (4), Mid-Level (4), Senior (4), Principal / Staff (4) roles with 4 fundamental, 4 intermediate, 4 advanced, 4 staff exercises tailored to Backend & Systems.
What are Rust's three ownership rules, and what is the difference between Move and Copy semantics?
How do borrowing rules (&T vs &mut T) and Non-Lexical Lifetimes (NLL) prevent data races at compile time?
What is the difference between String, &str, and Cow<'a, str>, and when should you choose each?
How do Option<T>, Result<T, E>, and the ? operator replace nulls and exceptions in Rust?
How do Rust lifetimes ('a) and lifetime elision rules work, and when is 'static required?
Compare static dispatch (impl Trait / generics) vs dynamic dispatch (dyn Trait), including object safety.
Frequently Asked Technical Interview Questions (Rust)
Essential theoretical concepts, architecture trade-offs, and runtime design questions asked by hiring committees.
How do Ownership, Borrowing, and Lifetimes ensure memory safety without a garbage collector?
What is the difference between Rc<RefCell<T>> and Arc<Mutex<T>>?
Why does Rust async/await require Pin for Futures?
What do the Send and Sync marker traits guarantee?
Pair Interview Prep with Cheat Sheets & Roadmaps
Review syntax formulas on our interactive cheat sheets, test your skills in technical quizzes, and study high-scale system designs.
Want to practice other technologies?
Explore our comprehensive technical interview tracks across all core technology stacks.