Rust interview questions and answers for developers
Rust interview questions center on ownership: who owns a value, when it moves, how long a borrow may live, and how the compiler proves there are no data races. Expect borrowing rules, lifetimes, traits and generics, enums with match, Result and Option with the ? operator, smart pointers such as Box, Rc, Arc and RefCell, Send and Sync, async basics and when unsafe is justified. The strongest answers read a borrow checker error aloud and explain what bug it prevented.
By Evin JohnPublished 9 min read
How Rust interviews are run
Rust shows up in infrastructure, databases, networking, blockchain, embedded systems, developer tools and performance-critical services. Because fewer candidates know it deeply, many teams hire strong engineers from C++ or Go and test whether they can reason about ownership. Expect a language conversation, a coding task in Rust where the borrow checker becomes part of the interview, and for senior roles a discussion of concurrency, async runtimes and API design.
- Ownership screenMoves, borrows, lifetimes, String versus &str. Interviewers often show compiler errors and ask what they mean.
- Coding in RustA parser, a small CLI, a data structure, or an algorithm problem. Fighting the borrow checker is normal; explaining why it complains is the skill.
- Concurrency and asyncShare state across threads, pick between channels and Arc with a Mutex, explain what an async function returns and who polls it.
- Design reviewError types for a library, trait design, when to use generics versus dyn, and how unsafe code is reviewed.
Ownership and borrowing questions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What are the ownership rules? | Ownership | Each value has one owner; when the owner goes out of scope the value is dropped; ownership can move to another binding or function, after which the old name is unusable. |
| What are the borrowing rules? | References | At any moment you may have either any number of shared references or exactly one mutable reference to a value, and references must not outlive it. |
| Copy versus Clone? | Traits | Copy types such as integers, and structs that derive Copy because all their fields are Copy, are duplicated implicitly with a bitwise copy. Clone is an explicit, possibly expensive duplication, like a String's heap buffer. |
| String versus &str? | Strings | String owns a growable UTF-8 buffer on the heap. &str is a borrowed view of UTF-8 bytes, from a String, a literal or a slice. Take &str in parameters to accept both. |
| Why can you not index a String by an integer? | UTF-8 | Characters can take one to four bytes, so an index would not be constant time or might split a character. Use chars, bytes or a byte range at a known boundary. |
| What does Drop do? | Destruction | It runs cleanup when a value goes out of scope, in reverse order of declaration. It is how files, locks and sockets release themselves. |
| What is a slice? | Views | A reference to a contiguous part of an array, vector or string: a pointer plus a length, with the borrow rules applying to the original. |
let s = String::from("hi");
let t = s; // ownership moves to t
println!("{s} {t}"); // error[E0382]: borrow of moved value: `s`
let mut v = vec![1, 2, 3];
let first = &v[0]; // shared borrow of v
v.push(4); // error[E0502]: cannot borrow `v` as mutable
// because it is also borrowed as immutable
println!("{first}");The second error is the one to explain in an interview. push may reallocate the vector, which would leave first pointing at freed memory. In C++ the same code compiles and is undefined behavior; in Rust the borrow rules turn it into a compile error.
Lifetimes
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {
if a.len() >= b.len() { a } else { b }
}
let r;
{
let x = 5;
r = &x; // error[E0597]: `x` does not live long enough
}
println!("{r}");- What does a lifetime annotation actually do? It names a relationship between references so the compiler can check it. It never makes a value live longer.
- What are the elision rules in short? Each input reference gets its own lifetime; with one input, the output borrows from it; with &self, the output borrows from self. When none applies, you annotate.
- What does 'static mean? The reference can be valid for the whole program, like a string literal. As a bound on a type, T: 'static means the type holds no short-lived borrows, which is why thread::spawn requires it.
- When does a struct need a lifetime parameter? When it stores a reference, such as a parser holding
&'a strof its input. Often owning the data is simpler.
Traits, generics, enums and match
enum Shape {
Circle { r: f64 },
Rect { w: f64, h: f64 },
}
fn area(s: &Shape) -> f64 {
match s {
Shape::Circle { r } => std::f64::consts::PI * r * r,
Shape::Rect { w, h } => w * h,
}
}| Question | What it tests | What a strong answer shows |
|---|---|---|
| Generics with trait bounds versus dyn Trait? | Dispatch | Generics are monomorphized: fast static calls, bigger binaries. A trait object such as Box<dyn Trait> uses a vtable, allowing mixed types in one collection at the cost of an indirect call. |
| What makes a trait object-safe? | Trait objects | Roughly, methods must not be generic and must not return Self by value, so a vtable can describe them. The current reference calls this dyn compatibility. |
| What is the orphan rule? | Coherence | You can implement a trait for a type only if your crate defines the trait or the type. It stops two crates from conflicting; the newtype pattern works around it. |
| Why does match have to be exhaustive? | Safety | Adding an enum variant forces every match to handle it, so new states cannot slip through unnoticed. A wildcard arm opts out deliberately. |
| What are associated types for? | Trait design | One natural type per implementation, like Iterator's Item, instead of a generic parameter callers must specify. |
| What do derive macros give you? | Boilerplate | Implementations of Debug, Clone, PartialEq, Hash and others generated from the fields, as long as every field implements them. |
Result, Option and the ? operator
#[derive(Debug)]
enum ConfigError {
Io(std::io::Error),
Parse(std::num::ParseIntError),
}
impl From<std::io::Error> for ConfigError {
fn from(e: std::io::Error) -> Self { ConfigError::Io(e) }
}
impl From<std::num::ParseIntError> for ConfigError {
fn from(e: std::num::ParseIntError) -> Self { ConfigError::Parse(e) }
}
fn read_port(path: &str) -> Result<u16, ConfigError> {
let text = std::fs::read_to_string(path)?;
let port = text.trim().parse::<u16>()?;
Ok(port)
}- Option versus Result? Option says a value may be absent with no reason given. Result carries an error explaining the failure. Convert with ok_or or ok when crossing between them.
- When is unwrap acceptable? In tests, quick prototypes, or where a failure would be a bug and you would rather crash. In library code prefer expect with a message, or return the error.
- panic versus Result? Result is for failures the caller can handle, like a missing file. panic is for broken invariants. Libraries should rarely panic on input.
- How do libraries and applications differ on error types? Libraries usually define their own error enum so callers can match on it, often with the thiserror crate. Applications often use one boxed error type, for example with anyhow, and add context as errors bubble up.
Smart pointers, Send and Sync
| Type | What it gives you | Typical use |
|---|---|---|
| Box<T> | Single owner, value on the heap | Recursive types, large values, trait objects. |
| Rc<T> | Shared ownership with a non-atomic count, one thread only | Graphs or trees where several parts own a node. |
| Arc<T> | Shared ownership with an atomic count, safe across threads | Config or caches shared by worker threads. |
| RefCell<T> | Borrow rules checked at runtime, panics on violation | Interior mutability inside an Rc on one thread. |
| Mutex<T> or RwLock<T> | Locked interior mutability across threads | Shared mutable state behind an Arc. |
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::{Arc, Mutex};
use std::thread;
let shared = Rc::new(RefCell::new(vec![1]));
let other = Rc::clone(&shared);
other.borrow_mut().push(2);
println!("{:?} {}", shared.borrow(), Rc::strong_count(&shared));
let total = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..4)
.map(|_| {
let total = Arc::clone(&total);
thread::spawn(move || {
*total.lock().unwrap() += 1;
})
})
.collect();
for h in handles {
h.join().unwrap();
}
println!("{}", *total.lock().unwrap());- What do Send and Sync mean? A Send type can be moved to another thread. A Sync type can be shared by reference between threads. The compiler derives both automatically from a type's fields.
- Why can Rc not cross threads? Its reference count is not atomic, so it is not Send. Moving one into thread::spawn fails with error E0277, and the fix is Arc.
- Can Rc leak memory? Yes. A cycle of Rc pointers never reaches zero. Use Weak for back references such as a child pointing at its parent.
- What happens if you call borrow_mut twice on a RefCell? The second call panics at runtime, because the rule the compiler normally checks is now checked while the program runs.
- What does the compiler rule out, and what not? Safe Rust prevents data races. It does not prevent deadlocks, logic races or leaks.
Async basics and unsafe
- What does an async fn return? A future: a state machine that does nothing until polled. An executor such as Tokio polls it, and the future registers a waker to be polled again when progress is possible.
- Why does Rust need a separate async runtime? The standard library defines the Future trait but ships no executor, so applications pick one that fits, such as Tokio for network services.
- What goes wrong if you block inside async code? A blocking call such as a synchronous file read or a long computation stalls the executor thread and every task scheduled on it. Use spawn_blocking or async APIs.
- Why do some futures need Pin? A future may hold references into itself across await points, so it must not move in memory once polled. Pin expresses that promise.
- What does unsafe allow? Dereferencing raw pointers, calling unsafe functions including FFI, accessing mutable statics, implementing unsafe traits and accessing union fields. The borrow checker still runs; you take on the invariants it cannot see.
- How should unsafe code be reviewed? Keep it small and inside a safe abstraction, write a SAFETY comment with the invariant each block relies on, and test it with Miri where possible.
Senior and scenario questions
| Scenario | What it tests | What a strong answer shows |
|---|---|---|
| A struct method needs to mutate one field while iterating another. | Borrow splitting | Borrow the fields separately rather than calling a method on all of self, or restructure into smaller types. |
| Clone calls are everywhere in a codebase. | Ownership design | Some clones are fine and cheap, such as an Arc. Many signal unclear ownership: pass references, move values, or reshape data so one owner is obvious. |
| A Tokio service stalls under load with low CPU. | Async pitfalls | Look for blocking calls on the runtime or a std Mutex guard held across an await. Move blocking work to spawn_blocking and keep guards short. |
| You are wrapping a C library. | FFI | A thin unsafe layer that mirrors the C API, then a safe wrapper that owns handles with Drop and converts error codes to Result. |
| Compile times are hurting the team. | Tooling | Split crates, trim generic-heavy dependencies, check which crates dominate the build timing report, and use incremental builds in development. |
Fictional example
- In a garbage-collected language, the runtime keeps memory alive as long as anything can reach it. Rust has no collector, so the compiler checks two things instead: every value has one owner that frees it, and references obey a simple rule, many readers or one writer, never both. When I ported a log-processing tool from Go, my first version stored references to lines inside a struct while the buffer they came from was being refilled. Go would have kept the old buffer alive; Rust refused to compile it, which in C would have been a use-after-free. I switched to owning the few fields I needed, and the result was simpler and faster than the original.
Three-week Rust preparation plan
- Week 1: ownership, borrowing and lifetimes. Recreate each compiler error on this page, read the full message, and explain the bug it prevents.
- Week 1, continued: String and &str, slices, Copy and Clone, Drop order.
- Week 2: traits, generics and trait objects, enums and match, then an error type for a small library with From conversions and the ? operator.
- Week 3: Rc, RefCell, Arc and Mutex, a threaded program and a Tokio program that fetches in parallel with a timeout.
- Week 3, final days: a timed exercise such as a tokenizer or an LRU cache, then a self-review for unnecessary clones and unwraps.
Rust is easiest to discuss next to the languages it is compared with. C++ interview questions cover the same ownership ideas without compiler enforcement, and Go interview questions show a garbage-collected approach to safe concurrency. For the role around the language, see software engineer interview questions.
Reading a borrow checker error aloud and explaining it is a skill worth rehearsing with a record of what you said. Natively, an AI interview assistant for Mac and Windows, transcribes your mock Rust sessions for later review. While practicing it can read a problem or compiler output from a screenshot, give a hint or an outline, and with Pro or the free trial use the résumé and job description you add. Sessions and notes stay saved so you can revisit them.
Questions people ask
What Rust questions are asked in interviews?
Ownership and moves, the borrowing rules, lifetimes, String versus &str, traits and generics versus trait objects, enums with match, Result and Option with the ? operator, smart pointers, Send and Sync, and async basics.
How do I explain ownership and borrowing in a Rust interview?
State the rules: one owner per value, dropped when the owner goes out of scope, and either many shared borrows or one mutable borrow at a time. Then show a compiler error and the bug it prevents, such as a reference into a vector that push could reallocate.
What Rust topics matter for experienced developers?
Error type design, generics versus dyn, Arc with Mutex and the limits of what the compiler rules out, async runtimes and blocking pitfalls, FFI and how unsafe code is kept small and documented.
Do Rust interviews include coding?
Usually. Common tasks are a parser, a small CLI, a data structure or an algorithm in Rust. Interviewers watch how you respond to the borrow checker as much as the final code.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
