Rust interviews test whether you can work with the compiler rather than against it. Expect code that fails to compile and a request to explain the error, a design question about traits or error types, and at least one question about threads or async. Systems and infrastructure teams add unsafe code and performance: what clone() costs, why a future is not Send, how a C string ends up dangling.
Candidates usually slip by treating the borrow checker as an obstacle. They add .clone() or Rc<RefCell<_>> until errors stop, which compiles but tells the interviewer they could not name the conflict. Other common misses: believing 'static means "lives forever", assuming Arc makes data mutable, and blocking inside async code. Strong answers read the error code, say which rule it enforces, and choose the fix that keeps ownership honest.
The 30 questions below are grouped into five areas: ownership, borrowing and lifetimes; traits, generics and error handling; smart pointers and interior mutability; concurrency and async; and unsafe code, FFI and performance. Answers reflect current stable Rust and the 2024 edition, and the page ends with prep advice, a short quiz and an FAQ.
Advanced30 questions
Rust Interview Questions
Practice Rust interview questions on ownership, borrowing, lifetimes, traits, error handling, smart pointers, concurrency, async, unsafe code and performance, with worked answers.
Every Rust interview starts here, because ownership has no equivalent in Python, Java or Go. Interviewers show code that fails to compile and watch how you read the error: do you name the conflict, or start adding .clone() until it goes away?
One rule sits behind every borrow error. At any point a value has either any number of shared references (&T) or exactly one mutable reference (&mut T), and no reference may outlive the value. Since non-lexical lifetimes arrived in Rust 2018, a borrow ends at its last use, not at the end of the block.
Ownership, Borrowing and Lifetimes
This fails with error[E0382]: borrow of moved value: s1: let s1 = String::from("fill"); let s2 = s1; println!("{s1}");. The same three lines with an i32 compile. Why?
EasyOwnership, Borrowing and Lifetimes
Sample Answer
String owns a heap buffer, so let s2 = s1; moves ownership: the pointer, length and capacity are copied into s2, and s1 can no longer be used. If both stayed valid, both would free the same buffer when they went out of scope. i32 implements Copy, so assignment duplicates the bits and the original stays usable. A type can be Copy only if all its fields are Copy and it has no Drop implementation, which rules out String, Vec and Box. The fix depends on intent: borrow with let s2 = &s1; if you only need to read, call s1.clone() if you really need two independent strings, or reorder the code so s1 is used before it moves.
Rust
1fnmain(){2let s1 =String::from("fill");3let s2 =&s1;// borrow instead of move4println!("{s1} {s2}");56let a =7_i32;7let b = a;// i32 is Copy: a is still usable8println!("{a} {b}");9}
let first = &v[0]; v.push(4); println!("{first}"); fails with E0502. Why does Rust reject it, and why does it compile if you delete the println!?
MediumOwnership, Borrowing and Lifetimes
Sample Answer
The error reads cannot borrow v as mutable because it is also borrowed as immutable. push takes &mut self, and first is a shared borrow that is still in use afterwards, so the two overlap. This is not pedantry: push may reallocate the buffer, which would leave first pointing at freed memory, the same bug C++ calls iterator invalidation. Delete the println! and first is never used after the push. With non-lexical lifetimes, a borrow ends at its last use rather than at the end of the block, so the shared borrow is already over when push runs. Fixes: copy the value out (let first = v[0]; works for Copy types), take the reference after the push, or keep an index instead of a reference.
Why does &s[0..1] panic when s is "élan", why does s[0] not compile at all, and how do you get the first character safely?
EasyOwnership, Borrowing and Lifetimes
Sample Answer
String and &str hold UTF-8 bytes, and range indexing counts bytes. é takes two bytes, so 0..1 ends in the middle of a character and the slice panics with a message that byte index 1 is not a char boundary. Rust refuses to produce invalid UTF-8 rather than hand back garbage. s[0] fails with E0277, "the type str cannot be indexed by {integer}", because a byte position is not a character position and the language will not pretend it is. Use s.chars().next() for the first char, s.char_indices() to find valid byte offsets, or s.get(0..1), which returns None instead of panicking. Remember that .len() counts bytes: "élan".len() is 5.
Rust
1fnmain(){2let s ="élan";3assert_eq!(s.len(),5);// bytes, not characters4assert_eq!(s.chars().next(),Some('é'));5assert_eq!(s.get(0..1),None);// not a char boundary6assert_eq!(s.get(0..2),Some("é"));7}
fn longest(a: &str, b: &str) -> &str fails with E0106, missing lifetime specifier. Fix it and explain what the annotation promises.
MediumOwnership, Borrowing and Lifetimes
Sample Answer
The return type is a reference, so the compiler must know which input it borrows from, and the elision rules cannot decide: each elided input reference gets its own lifetime; if there is exactly one input lifetime, the output gets it; if one input is &self or &mut self, the output gets that one. With two plain inputs, none applies. fn longest<'a>(a: &'a str, b: &'a str) -> &'a str says the result is valid for as long as both inputs are, which in practice means the shorter of the two. Annotations never change how long a value lives; they describe a relationship the compiler checks at every call site, so a caller that uses the result after b is dropped gets E0597, b does not live long enough.
Rust
1fnlongest<'a>(a:&'astr, b:&'astr)->&'astr{2if a.len()>= b.len(){ a }else{ b }3}45fnmain(){6let a =String::from("limit");7let r;8{9let b =String::from("market");10 r =longest(&a,&b);11println!("{r}");// fine: b is still alive12}13// println!("{r}"); // E0597: `b` does not live long enough14}
A cache helper takes &mut HashMap<u32, String>, returns the value from map.get(&key) if present, and otherwise inserts a new value and returns it. It looks correct but fails with E0502 on the insert. Why, and what is the idiomatic version?
HardOwnership, Borrowing and Lifetimes
Sample Answer
The returned reference must live as long as the caller's borrow of the map, and today's borrow checker applies that requirement to the map.get borrow on every path, including the one that falls through to map.insert. So it sees a shared borrow that must last until the function returns, overlapping a mutable borrow, even though the early return means they never coexist. This is a known false positive, listed as problem case #3 in the non-lexical lifetimes RFC (RFC 2094). Polonius, the next-generation borrow checker, is designed to accept it, but stable rustc still rejects it. The entry API is better code anyway: map.entry(key).or_insert_with(...) performs one hash lookup instead of two and returns the reference directly.
Rust
1usestd::collections::HashMap;23fnget_or_insert(map:&mutHashMap<u32,String>, key:u32)->&String{4 map.entry(key).or_insert_with(||format!("value {key}"))5}67fnmain(){8letmut m =HashMap::new();9println!("{}",get_or_insert(&mut m,7));// value 710}
thread::spawn(|| println!("{:?}", data)) fails with E0373, closure may outlive the current function. A teammate suggests making data'static. What does 'static mean here, and what are the better fixes?
MediumOwnership, Borrowing and Lifetimes
Sample Answer
std::thread::spawn requires its closure to be Send + 'static, because the new thread can outlive the function that spawned it. A T: 'static bound means the type holds no references shorter than 'static; it does not mean the value lives forever. An owned Vec<u64> satisfies 'static and can still be dropped a millisecond later. So give the thread owned data: move || transfers data into the closure, or give each thread its own Arc clone when several need it. When worker threads only need to read locals and finish before the function returns, use std::thread::scope (stable since Rust 1.63). Every thread spawned inside the scope is joined before scope returns, so borrowing locals is allowed.
Rust
1usestd::thread;23fnmain(){4let data =vec![1u64,2,3,4,5,6];5let(left, right)= data.split_at(3);6let total:u64=thread::scope(|s|{7let a = s.spawn(|| left.iter().sum::<u64>());8let b = s.spawn(|| right.iter().sum::<u64>());9 a.join().unwrap()+ b.join().unwrap()10});11println!("{total}");// 2112}
Traits are how Rust does polymorphism, and interviewers use them to test design judgment: when static dispatch fits, when a trait object is the right call, and how to shape error types so callers can act on them.
Hold on to one distinction. Generics are resolved at compile time and trait objects at runtime. fn f<T: Shape>(x: &T) is monomorphized into one copy per type and can be inlined, while &dyn Shape is a single copy that calls through a vtable. Most trait design questions come down to choosing between the two.
Traits, Generics and Error Handling
You are writing a renderer that keeps circles, rectangles and polygons in one list and calls area() on each. Would you use generics or trait objects, and what does each compile to?
MediumTraits, Generics and Error Handling
Sample Answer
A list of mixed types needs trait objects: Vec<Box<dyn Shape>>. Each Box<dyn Shape> is a fat pointer, 16 bytes on a 64-bit target, holding a data pointer and a vtable pointer, and area() becomes an indirect call that the compiler usually cannot inline. Generics such as fn total<T: Shape>(items: &[T]) are monomorphized: the compiler emits one copy per concrete type, calls are direct and inlinable, and binary size grows with each instantiation. But a Vec<T> holds only one T. If the set of shapes is closed and known, an enum with a match is often fastest, with no allocation per item and no indirect call. Keep dyn for open sets, such as handlers that other crates add.
You add fn scaled(&self, k: f64) -> Self to your Shape trait, and every Box<dyn Shape> in the codebase now fails with E0038. Why, and how do you keep the method?
HardTraits, Generics and Error Handling
Sample Answer
A trait object calls methods through a vtable with one function pointer per method, built without knowing the concrete type. A method returning Self cannot work through it, because the caller does not know the size of Self. Generic methods break it too, since they would need one vtable entry per type argument, and so do associated functions with no self, like fn new() -> Self, which have no value to find a vtable through. Any of these makes the trait not dyn compatible (older material says object safe), and rustc reports E0038, "the trait Shape is not dyn compatible". Add where Self: Sized to the method: it is left out of the vtable, stays callable on concrete types, and dyn Shape works again.
Rust
1traitShape{2fnarea(&self)->f64;3fnscaled(&self, k:f64)->SelfwhereSelf:Sized;// not in the vtable4}5structCircle{ r:f64}6implShapeforCircle{7fnarea(&self)->f64{3.14159*self.r *self.r }8fnscaled(&self, k:f64)->Self{Circle{ r:self.r * k }}9}10fnmain(){11let shapes:Vec<Box<dynShape>>=vec![Box::new(Circle{ r:1.0}.scaled(2.0))];12println!("{:.2}", shapes[0].area());// 12.5713}
Why is Iterator written with an associated type (type Item;) while From<T> takes a generic parameter? How would you choose for your own trait?
MediumTraits, Generics and Error Handling
Sample Answer
A generic parameter allows many implementations of the trait for one type. String implements From<&str>, From<char>, From<Box<str>> and more, and the argument type picks one. An associated type allows exactly one implementation per type: into_iter() on a Vec<u32> yields u32 and nothing else, so Item is an output determined by the implementing type. That keeps call sites clean. You write I: Iterator<Item = u32>, or just I: Iterator, instead of threading an extra type parameter through every function, and inference never has to choose between implementations. A practical test: if it makes sense for one type to implement the trait in several ways, use a generic parameter. If the type alone determines the answer, use an associated type.
Write a function that parses a port number from a string and returns a Result. What exactly does the ? operator do, and why does it fail on an Option inside that function?
EasyTraits, Generics and Error Handling
Sample Answer
On a Result, ? is shorthand for a match: Ok(v) makes the expression evaluate to v, and Err(e) returns early from the function with Err(From::from(e)). The conversion is the part people forget. ? turns the error into the function's own error type through a From impl, so a ParseIntError can become your own error enum or a Box<dyn Error>. ? also works on Option, returning None early, but it does not mix the two, so using it on an Option in a function returning Result fails with E0277. Convert with .ok_or(...) or .ok_or_else(...). Let main return Result<(), Box<dyn Error>> so ? works there too; an Err from main exits with a non-zero status.
Rust
1usestd::error::Error;23fnparse_port(s:&str)->Result<u16,Box<dynError>>{4let port:u16= s.trim().parse()?;// ParseIntError -> Box<dyn Error>5if port ==0{6returnErr("port must be non-zero".into());7}8Ok(port)9}1011fnmain()->Result<(),Box<dynError>>{12println!("{}",parse_port(" 8080 ")?);13Ok(())14}
You maintain a library crate and an application that uses it. How should their error types differ, and where do panics belong?
MediumTraits, Generics and Error Handling
Sample Answer
A library should return a concrete error type that callers can match on: usually an enum with one variant per failure a caller might handle differently. It implements Debug, Display and std::error::Error, has From impls so ? converts underlying errors, and returns the wrapped cause from source(). Derive-macro crates generate exactly that boilerplate. Mark the enum #[non_exhaustive] so adding a variant later is not a breaking change. An application mostly reports errors instead of branching on them, so one dynamic type such as Box<dyn Error + Send + Sync>, with context added at each layer (which file, which request), is simpler. Dynamic error crates add context methods and backtraces on top. In both, panics are for bugs: never unwrap() input that a user or the network controls.
A function declared to return impl Fn(f64) -> f64 picks one of two closures based on a flag, and fails with E0308, if and else have incompatible types. Why, and what are the fixes?
HardTraits, Generics and Error Handling
Sample Answer
impl Trait in return position stands for one concrete type that the function chooses and hides from callers. Every closure has its own unique anonymous type, even when two closures have identical signatures, so the two branches return different types. Fixes: return Box<dyn Fn(f64) -> f64> and box both branches, which costs a heap allocation and an indirect call. Or write a small enum with a method that does the work, which keeps static dispatch. Or, when neither closure captures anything, declare the return type as the function pointer fn(f64) -> f64, which both closures coerce to. The same one-type rule explains why a function returning impl Iterator cannot return a map adapter on one path and a filter on another.
Rust
1fnpricer(discount:bool)->Box<dynFn(f64)->f64>{2if discount {3Box::new(|p| p *0.9)4}else{5Box::new(|p| p)6}7}89fnmain(){10println!("{}",pricer(true)(100.0));// 9011}
Plain ownership cannot express a graph, a shared cache or a value that two threads update. Smart pointers and interior mutability fill those gaps, and interviewers check that you know what each one costs and which guarantees move from compile time to runtime.
The key idea: Rc and Arc give shared ownership but only shared (&) access. Mutating through them takes interior mutability, RefCell on one thread and Mutex, RwLock or atomics across threads, and each of those enforces the borrowing rules at runtime instead of compile time.
Smart Pointers and Interior Mutability
enum List { Cons(i32, List), Nil } fails with E0072, recursive type List has infinite size. Explain and fix it, then name two other reasons to use Box.
EasySmart Pointers and Interior Mutability
Sample Answer
The compiler must know every type's size at compile time. A List that contains a List directly would be an i32 plus another List, recursively, with no end. Box<List> is a pointer to a heap allocation, so the field becomes 8 bytes on a 64-bit target and the size is finite. The other common uses are trait objects (Box<dyn Error>, Vec<Box<dyn Shape>>), where the concrete size is not known at compile time, and moving a large value to the heap so that moving it copies one pointer instead of many bytes. Box has exactly one owner and frees its allocation when dropped, the same model as C++ unique_ptr.
Rust
1enumList{2Cons(i32,Box<List>),3Nil,4}5useList::{Cons,Nil};67fnsum(l:&List)->i32{8match l {Cons(v, rest)=> v +sum(rest),Nil=>0}9}1011fnmain(){12let l =Cons(1,Box::new(Cons(2,Box::new(Nil))));13println!("{}",sum(&l));// 314}
You share a config between worker threads with Rc<Config> and get E0277, Rc<Config> cannot be sent between threads safely. Why does Rust forbid this, and what changes with Arc?
MediumSmart Pointers and Interior Mutability
Sample Answer
Rc keeps its strong and weak counts in plain integers and updates them with ordinary loads and stores. Two threads cloning or dropping the same Rc at once could lose an update, then free the value while it is still in use, or never free it. So Rc implements neither Send nor Sync, and thread::spawn requires a Send closure. Arc does the same job with atomic counts, which makes it Send and Sync when T: Send + Sync, at the price of an atomic read-modify-write on every clone and drop. Use Rc inside one thread, for example nodes in a single-threaded parser, and Arc when data crosses threads. Neither gives mutable access: an Arc<Config> is read-only unless Config contains a Mutex or atomics.
A struct stores RefCell<Vec<Order>>. One method iterates over self.orders.borrow() and, inside the loop, calls a helper that does self.orders.borrow_mut(). It compiles but panics at runtime. Explain.
MediumSmart Pointers and Interior Mutability
Sample Answer
RefCell moves the borrowing rules from compile time to runtime. borrow() returns a Ref guard and increments a counter of shared borrows. borrow_mut() returns a RefMut and requires that no other borrow is alive. The Ref from the loop is still alive when the helper calls borrow_mut(), so it panics; current rustc prints "RefCell already borrowed". The compiler cannot catch it, since both calls take &self. Fixes: finish with the shared borrow first (collect what you need, drop the guard, then mutate), pass &mut Vec<Order> into the helper instead of letting it borrow again, or use try_borrow_mut(), which returns a Result instead of panicking. Keep RefCell guards short-lived, and never hold one across a call into code you do not control.
You model a tree with Rc everywhere, and each child keeps an Rc to its parent. Memory grows without bound as trees are built and discarded. Why, and what does Weak change?
MediumSmart Pointers and Interior Mutability
Sample Answer
Each parent holds an Rc to each child and each child holds one back, so every node has a strong count of at least one coming from the other side. When the last outside handle to the root is dropped, the counts fall but never reach zero, Drop never runs, and the nodes leak. Rust's safety guarantees do not cover leaks; std::mem::forget is a safe function. Make the back edge a Weak, created with Rc::downgrade(&parent). A Weak counts toward Rc::weak_count but not Rc::strong_count, so it does not keep the parent alive, and upgrade() returns an Option<Rc<_>> that is None once the parent is gone. Ownership points down the tree and observation points up.
A method locks self.state, a std::sync::Mutex, and while holding the guard calls another method that locks the same mutex. The thread hangs. Separately, after a worker panics, every lock() returns Err. Explain both.
HardSmart Pointers and Interior Mutability
Sample Answer
std::sync::Mutex is not re-entrant. The docs leave locking a mutex the current thread already holds unspecified and promise only that the second lock() will not return; it may deadlock or panic. Rust prevents data races at compile time, not deadlocks. Restructure so the inner method takes &mut State from the caller's guard instead of locking again. The Err is poisoning. If a thread panics while holding the guard, the mutex is marked poisoned because the data may be half-updated, and later lock() calls return Err(PoisonError). lock().unwrap() propagates the panic, which is often right. If you can repair the state, take the guard with into_inner() on the error, and call clear_poison() (stable since Rust 1.77) to reset the flag.
You need a request counter, a config that is read constantly and reloaded hourly, and a cache map, all shared across threads. Which primitive do you pick for each?
MediumSmart Pointers and Interior Mutability
Sample Answer
The counter is a single integer, so use AtomicU64 with fetch_add(1, Ordering::Relaxed): no lock, and Relaxed is enough because no other data depends on its value. For the config, readers vastly outnumber writers. Store it as RwLock<Arc<Config>>: a reader holds the read lock only long enough to clone the Arc, then uses that snapshot with no lock held, and a reload swaps in a new Arc under the write lock. The cache is a mutable map, so Mutex<HashMap<K, V>> is the simple starting point. If profiling shows contention, shard it into several maps selected by key hash, each with its own lock. Cell and RefCell are out for all three, since neither is Sync.
Rust
1usestd::collections::HashMap;2usestd::sync::atomic::{AtomicU64,Ordering};3usestd::sync::{Arc,Mutex,RwLock};4structConfig{ limit:u32}5structShared{6 requests:AtomicU64,7 config:RwLock<Arc<Config>>,8 cache:Mutex<HashMap<String,String>>,9}10fnhandle(s:&Shared)->u32{11 s.requests.fetch_add(1,Ordering::Relaxed);12let cfg =Arc::clone(&s.config.read().unwrap());// lock held only here13 cfg.limit
14}
Fearless concurrency is a big reason teams adopt Rust, so interviewers test whether you know what the compiler actually guarantees. It rules out data races through the Send and Sync traits. It does not rule out deadlocks or logic races, and async code adds failure modes of its own.
What matters most is that thread safety is part of a type. Send means a value can move to another thread, Sync means it can be shared by reference, and the compiler derives both from a type's fields. Most concurrency errors in an interview come from an Rc, a RefCell or a lock guard ending up where one of those traits is required.
Concurrency and Async
Write a program where four threads each add 1,000 to a shared counter, then print the total. Explain why each wrapper is there.
EasyConcurrency and Async
Sample Answer
thread::spawn needs a 'static closure, so the threads cannot borrow a local counter; they need shared ownership. Arc provides it, with an atomic reference count so it can cross threads. Shared ownership gives only & access, so mutation needs a lock: Mutex<u64>, whose lock() returns a guard that derefs to the value and unlocks when dropped. Each thread gets its own Arc::clone, moved into its closure. join() waits for a thread and returns Err if it panicked, which unwrap turns into a panic in main. For a plain counter AtomicU64 is lighter than a mutex, but Arc<Mutex<T>> is the shape to know, because it works for any data.
Rust
1usestd::sync::{Arc,Mutex};2usestd::thread;34fnmain(){5let total =Arc::new(Mutex::new(0u64));6let handles:Vec<_>=(0..4).map(|_|{7let total =Arc::clone(&total);8thread::spawn(move||{9for _ in0..1000{*total.lock().unwrap()+=1;}10})11}).collect();12for h in handles { h.join().unwrap();}13println!("{}",*total.lock().unwrap());// 400014}
Define Send and Sync precisely, then classify Rc<T>, Arc<T>, RefCell<T>, Mutex<T> and MutexGuard<T>.
MediumConcurrency and Async
Sample Answer
T: Send means ownership of a T can move to another thread. T: Sync means &T can be shared between threads; formally, T is Sync exactly when &T is Send. Both are auto traits, so a struct gets them when all its fields have them. Rc<T> is neither, because its non-atomic count would race. Arc<T> is both when T: Send + Sync. RefCell<T> is Send when T is, since handing it to one other thread is fine, but never Sync, because its borrow counter is not atomic. Mutex<T> is Send and Sync when T: Send, which is how it makes a non-Sync value shareable. MutexGuard<T> is not Send, because some platforms require the locking thread to unlock. Raw pointers are neither.
A pipeline uses std::sync::mpsc. The consumer runs for msg in rx and the program never exits after all producer threads finish. Why?
MediumConcurrency and Async
Sample Answer
for msg in rx keeps receiving until the channel closes, and an mpsc channel closes only when every Sender has been dropped. The usual bug is cloning tx for each producer and keeping the original alive in main, so the sender count never reaches zero and the receiver waits forever. Call drop(tx) after spawning, or move the original into the last producer. Interviewers often follow up on capacity: mpsc::channel() is unbounded, so a fast producer can grow memory without limit, while mpsc::sync_channel(n) blocks senders once n messages are queued, which gives backpressure. And mpsc means single consumer: Receiver is not Sync, so workers cannot share it without a Mutex.
Rust
1usestd::sync::mpsc;2usestd::thread;34fnmain(){5let(tx, rx)=mpsc::sync_channel::<u32>(16);// bounded: backpressure6for id in0..3{7let tx = tx.clone();8thread::spawn(move|| tx.send(id).unwrap());9}10drop(tx);// or the loop never ends11letmut got:Vec<u32>= rx.iter().collect();12 got.sort();13println!("{got:?}");// [0, 1, 2]14}
In a Tokio service, one handler calls std::thread::sleep(Duration::from_secs(1)) to simulate a slow call, and latency jumps for unrelated requests. Another handler calls an async fn without .await, and nothing happens. Explain both.
MediumConcurrency and Async
Sample Answer
An async fn compiles to a state machine that implements Future. Calling it runs none of its body: it returns the future, and the body starts only when something polls it. That is why a call without .await, or without spawning it, does nothing, and rustc warns that futures do nothing unless awaited or polled. Polling happens on a small pool of worker threads, one per CPU core by default in Tokio's multi-threaded runtime, and a task gives its thread back only at an .await that is not ready. std::thread::sleep blocks the worker thread itself, so every task queued on that worker waits a full second. Use tokio::time::sleep(..).await, which suspends only the task, and move unavoidable blocking or CPU-heavy work to tokio::task::spawn_blocking.
An async function locks a std::sync::Mutex, then awaits a network call while the guard is still alive. Passing it to tokio::spawn fails with "future cannot be sent between threads safely". Why, and how do you fix it?
HardConcurrency and Async
Sample Answer
tokio::spawn on the multi-threaded runtime requires a Send + 'static future, because a task can be suspended on one worker and resumed on another. Every local that is alive across an .await becomes a field of the future's state machine, so the future is Send only if those locals are. std::sync::MutexGuard is not Send, so holding one across an .await makes the whole future non-Send, and the compiler's note names the guard and the .await. The error is doing you a favor: a task suspended while holding a blocking lock would stall every other task that wants it. Scope the guard so it is dropped before the .await, copying out what you need. If the lock really must span the await, use tokio::sync::Mutex.
Rust
1usestd::sync::{Arc,Mutex};23asyncfnrecord(hits:Arc<Mutex<u64>>){4let n ={5letmut g = hits.lock().unwrap();6*g +=1;7*g
8};// guard dropped here, before the await9send_metric(n).await;// the future is Send again10}1112asyncfnsend_metric(_n:u64){}
What problem does Pin solve, and why does Future::poll take self: Pin<&mut Self>? Where do Box::pin and pin! show up in everyday code?
HardConcurrency and Async
Sample Answer
An async block can keep a reference to one of its own locals across an .await, for example a slice of a buffer it owns. Both become fields of the same state machine, so the future is self-referential: if it moved in memory after being polled, that internal reference would point at the old location. Pin<&mut Self> in poll is the promise that once pinned, the value will not move again until it is dropped. Types that are safe to move anyway implement the auto trait Unpin, as most ordinary types do; compiler-generated futures generally do not. You meet pinning when you store or poll futures yourself: Box::pin for Pin<Box<dyn Future<Output = T>>> and recursive async functions, and std::pin::pin! (stable since Rust 1.68) to pin a future on the stack.
Systems roles that hire Rust engineers expect you to know where the safe language ends. Interviewers ask what unsafe permits, how to call C, and how you would show that an unsafe block is sound. Then they turn to speed: where allocations hide, what clone() costs, and whether iterators are really free.
The central idea is that unsafe does not switch off the borrow checker. It unlocks a short list of operations the compiler cannot verify, and you take over the job of upholding the invariants that safe code relies on. Breaking one is undefined behavior, exactly as in C++.
Unsafe Code, FFI and Performance
What does an unsafe block let you do that safe Rust does not, and what changed around unsafe in the 2024 edition?
MediumUnsafe Code, FFI and Performance
Sample Answer
Exactly five operations: dereference a raw pointer, call an unsafe function (including foreign functions), read or write a mutable static, implement an unsafe trait such as Send, and read a union field. Type checking, borrow checking of references and slice bounds checks all still apply inside the block. The 2024 edition, stable since Rust 1.85, tightened the edges. Extern blocks must be written unsafe extern "C" { ... }, and items inside can be marked safe fn. Attributes that can break linking take the unsafe(...) form, as in #[unsafe(no_mangle)]. The unsafe_op_in_unsafe_fn lint warns by default, so the body of an unsafe fn needs its own unsafe {} blocks. Taking a reference to a static mut is now an error under the deny-by-default static_mut_refs lint.
Code calls a C function that takes const char* like this: let p = CString::new(name).unwrap().as_ptr(); and then unsafe { c_log(p) }. Sometimes C prints garbage. Find the bug and write a correct call.
HardUnsafe Code, FFI and Performance
Sample Answer
CString::new(name).unwrap() creates a temporary that is dropped at the end of the let statement, so p points into freed memory by the time C reads it. Whether it seems to work depends on whether the allocator has reused that block yet, hence the intermittent garbage. rustc warns about this exact pattern. Bind the CString to a variable that outlives the call and pass owned.as_ptr(). A few more boundary rules: CString::new returns an error if the input contains an interior NUL byte; in the 2024 edition, foreign declarations go in an unsafe extern "C" block; structs passed by value need #[repr(C)]; memory is freed by whichever side allocated it; and since Rust 1.81 a panic unwinding out of an extern "C" function aborts the process.
Rust
1usestd::ffi::{CString, c_char};2unsafeextern"C"{3fnstrlen(s:*const c_char)->usize;4}5fnc_len(name:&str)->usize{6let owned =CString::new(name).expect("no interior NUL bytes");7// SAFETY: owned is NUL-terminated and outlives the call.8unsafe{strlen(owned.as_ptr())}9}10fnmain(){11println!("{}",c_len("AAPL"));// 412}
A teammate rewrites values.iter().filter(|v| **v > 0).map(|v| v * 2).sum::<i64>() as an indexed for loop because iterator chains look slow. Is the rewrite faster?
EasyUnsafe Code, FFI and Performance
Sample Answer
In a release build, no. Iterator adapters are generic structs, so filter, map and sum are monomorphized and inlined, and the optimizer compiles the chain into the same loop you would write by hand, often vectorized. The indexed version can even be slower: values[i] is bounds-checked unless the optimizer can prove i < len, which it manages for simple loops but not always, while the iterator never indexes. The rewrite only wins in debug builds, where every closure and every next() is a real function call and integer overflow is checked on each add; one measurement had an iterator chain about 40 times slower in debug than in release. Benchmark with --release, and read the assembly before trusting a micro-optimization.
Rust
1fntotal(values:&[i64])->i64{2 values.iter().filter(|v|**v >0).map(|v| v *2).sum()3}45fntotal_indexed(values:&[i64])->i64{6letmut s =0;7for i in0..values.len(){8if values[i]>0{ s += values[i]*2;}// bounds check unless proven9}10 s
11}
A profile shows a Rust service spending 30% of its time in memcpy and the allocator, mostly from .clone() calls added to get past the borrow checker. What does clone() cost for String, Vec<T> and Arc<T>, and how do you remove the clones?
EasyUnsafe Code, FFI and Performance
Sample Answer
clone() on a String or Vec<T> is a deep copy: a new heap allocation plus a copy of every element, so O(n) time and memory. On an Arc<T> or Rc<T> it copies a pointer and increments a reference count, which costs the same however large T is. So the expensive clones are of owned collections, and most of them can go. Take &str or &[T] parameters instead of String or Vec<T>, so callers lend data instead of copying it. Return borrowed data where lifetimes allow. Put large read-only data behind an Arc once and clone the handle. Use Cow<'_, str> when a function only sometimes needs to modify its input. And preallocate with Vec::with_capacity when building output in a loop.
What is size_of::<Option<Box<u64>>>() on a 64-bit target, and why? Why can a struct's fields sit in memory in a different order from the source, and when must you prevent it?
MediumUnsafe Code, FFI and Performance
Sample Answer
It is 8, the same as Box<u64>. A Box can never be null, so the compiler stores None as the null pointer and needs no separate tag. This niche optimization is guaranteed for Option of Box<T>, &T, &mut T, NonNull<T> and the NonZero integers, so Option<&T> can cross an FFI boundary as a nullable pointer. Struct layout is different: under the default repr(Rust) the compiler may reorder fields, usually to reduce padding, and promises little else. A struct of u8, u64, u8 takes 24 bytes in declaration order and 16 when reordered. When layout must be predictable, for C interop or a wire format mapped from bytes, add #[repr(C)], which keeps declaration order and C's alignment rules.
Implement split_at_mut for a &mut [i32] yourself. Why can't safe Rust express it, what makes the unsafe version sound, and how would you test it?
HardUnsafe Code, FFI and Performance
Sample Answer
Safe code would take &mut v[..mid] and &mut v[mid..], two mutable borrows of v at once, and the borrow checker rejects that with E0499 because it does not reason about disjoint ranges of one slice. The unsafe version builds both halves from a raw pointer with slice::from_raw_parts_mut. It is sound because of two facts: the assert! guarantees mid <= len, so both ranges stay in bounds, and the ranges do not overlap, so the two &mut never alias. Two overlapping &mut would be undefined behavior even if neither were written through. Record that reasoning in a // SAFETY: comment, keep the unsafe block small behind a safe signature, and run the tests under Miri (cargo +nightly miri test), which reports aliasing violations, out-of-bounds access and use-after-free.
Rust
1usestd::slice;23fnsplit_at_mut(v:&mut[i32], mid:usize)->(&mut[i32],&mut[i32]){4let len = v.len();5let ptr = v.as_mut_ptr();6assert!(mid <= len);7// SAFETY: mid <= len, so both ranges are in bounds and do not overlap.8unsafe{9(slice::from_raw_parts_mut(ptr, mid),10slice::from_raw_parts_mut(ptr.add(mid), len - mid))11}12}
When code fails to compile, read the error code and the labels under your code before changing anything, and say the conflict in one sentence. That habit is what interviewers watch for. The Read the borrow checker lesson works through real errors and their idiomatic fixes, including one the checker rejects even though the code is correct.
Classify common types by Send and Sync
Be able to say, without looking it up, whether Rc, Arc, RefCell, Mutex and MutexGuard are Send and Sync, and why. Most thread and async compile errors come down to this table. Threads, Send and Sync and Arc, Mutex, RwLock and atomics cover it with programs you can run.
Build one program with shared ownership end to end
Linked structures are where Rust feels hardest in a live round. Write an LRU cache or a thread pool once, from scratch, so Rc, Weak, RefCell, Arc and channels stop being abstract. Build an LRU cache and Build a thread pool are both realistic interview-sized builds.
Learn async from the executor up
Understand what a future is, what polling and waking mean, and why Send matters for spawned tasks before you lean on a runtime. Then the errors make sense. Async Rust and futures builds a tiny executor so you can see where a blocking call stalls everything.
You hold let first = &v[0]; and then call v.push(1), using first afterwards. Why is it rejected?
Frequently Asked Questions
Is Rust asked in software engineering interviews in 2026?
Yes, mostly at companies that run Rust in production: infrastructure and cloud providers, databases, networking and security tools, trading systems, blockchain projects and ML serving teams. There, expect a Rust-specific round on ownership, traits and concurrency. Elsewhere, Rust is usually allowed in general coding rounds but rarely required. If a job description lists Rust as the main language, prepare for questions about async and unsafe code as well as the basics.
Should I use Rust for algorithm coding rounds?
Only if you are fluent. The standard library covers what most problems need (Vec, HashMap, BTreeMap, BinaryHeap, VecDeque), but linked lists, trees with parent pointers and graphs push you toward Rc<RefCell<_>> or index-based designs, which cost time under pressure. Storing nodes in a Vec and referring to them by index is the usual trick. If you are still fighting the borrow checker in practice, pick a language you are faster in for algorithm rounds.
Which Rust version and edition should I know?
Know the 2024 edition, stable since Rust 1.85 in February 2025, and current stable Rust, which ships a new release every six weeks. Interviewers rarely ask about specific versions, but they notice outdated habits such as plain extern blocks or references to static mut. Async functions in traits (stable since 1.75) and std::thread::scope (since 1.63) are worth knowing because older material works around their absence.
How long does it take to prepare for a Rust interview?
If you already write Rust, two to four weeks of review is typical: ownership and lifetimes, traits and errors, then concurrency and async, with practice reading compiler errors throughout. Coming from C++, plan on four to six weeks, since the concepts map but the rules are stricter. Coming from Python or Java, allow two to three months, because ownership needs time and real code to become intuitive.
Do I need to know Tokio and async Rust?
For backend, networking and infrastructure roles, yes. Expect questions on why futures are lazy, what happens when you block inside async code, why spawned futures must be Send, and what Pin is for at a high level. You rarely need deep runtime internals. For systems roles focused on CPU-bound work, such as databases or compilers, threads, channels and atomics matter more than async.
Do Rust interviews cover unsafe code?
At the level of concepts, often. You should be able to list what unsafe allows, explain why it does not disable the borrow checker, write a small sound function such as split_at_mut, and describe how to call a C function safely. Deep unsafe work, like custom allocators or lock-free structures, comes up mainly for teams that build low-level libraries. Mentioning Miri as the way to test unsafe code is a good signal.
Written by
Dan Lee
Data & AI Lead
Dan is a seasoned data scientist and ML coach with 10+ years of experience at Google, PayPal, and startups. He has helped candidates land top-paying roles and offers personalized guidance to accelerate your data career.