Rust Interview Questions

Dan Lee's profile image
Dan LeeData & AI Lead
Last update
Rust Interview Questions

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.

Software EngineerSystems EngineerBackend EngineerBlockchain EngineerMachine Learning Infrastructure Engineer

Ownership, Borrowing and Lifetimes

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
1fn main() {
2    let s1 = String::from("fill");
3    let s2 = &s1;            // borrow instead of move
4    println!("{s1} {s2}");
5
6    let a = 7_i32;
7    let b = a;               // i32 is Copy: a is still usable
8    println!("{a} {b}");
9}
Learn this in the Rust course

Traits, Generics and Error Handling

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.

Rust
1trait Shape { fn area(&self) -> f64; }
2struct Circle { r: f64 }
3struct Rect { w: f64, h: f64 }
4impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r } }
5impl Shape for Rect { fn area(&self) -> f64 { self.w * self.h } }
6
7fn main() {
8    let shapes: Vec<Box<dyn Shape>> =
9        vec![Box::new(Circle { r: 1.0 }), Box::new(Rect { w: 2.0, h: 3.0 })];
10    let total: f64 = shapes.iter().map(|s| s.area()).sum();
11    println!("{total:.2}");                                   // 9.14
12    assert_eq!(std::mem::size_of::<Box<dyn Shape>>(), 16);   // fat pointer
13}
Learn this in the Rust course

Smart Pointers and Interior Mutability

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
1enum List {
2    Cons(i32, Box<List>),
3    Nil,
4}
5use List::{Cons, Nil};
6
7fn sum(l: &List) -> i32 {
8    match l { Cons(v, rest) => v + sum(rest), Nil => 0 }
9}
10
11fn main() {
12    let l = Cons(1, Box::new(Cons(2, Box::new(Nil))));
13    println!("{}", sum(&l));   // 3
14}
Learn this in the Rust course

Concurrency and Async

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
1use std::sync::{Arc, Mutex};
2use std::thread;
3
4fn main() {
5    let total = Arc::new(Mutex::new(0u64));
6    let handles: Vec<_> = (0..4).map(|_| {
7        let total = Arc::clone(&total);
8        thread::spawn(move || {
9            for _ in 0..1000 { *total.lock().unwrap() += 1; }
10        })
11    }).collect();
12    for h in handles { h.join().unwrap(); }
13    println!("{}", *total.lock().unwrap());   // 4000
14}
Learn this in the Rust course

Unsafe Code, FFI and Performance

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.

Learn this in the Rust course

How to Prepare for Rust Interviews

Read borrow checker errors label by label

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.

Measure performance in release mode only

Practice answering performance questions with numbers: compare an iterator chain and a loop in release mode, count allocations, and check size_of for the types you design. Zero-cost abstractions and measuring speed and Memory layout, Copy and Clone show how to do both.

How Ready Are You for Rust Interviews?

1 / 6
Borrowing

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.

Dan Lee's profile image

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.

Connect on LinkedIn