Skip to content
rusthacks.dev
Rust

Rust Interview Questions With Answers That Show Reasoning

Twelve Rust interview questions with answers that explain the why: ownership, borrowing, lifetimes, traits, Send and Sync, async, unsafe. Includes what a strong answer sounds like.

8 min read
Summarize in AI
Flat illustration for the post “Rust Interview Questions With Answers That Show Reasoning”, composed around lifetime.

Rust interviews test understanding, and the way to show understanding is to state a rule, run a small example and name the bug the rule prevents. A memorized definition earns a nod. A short example that fails to compile, with the error and the fix, shows you have actually met the thing. This post goes through the questions that come up most, ownership and borrowing, lifetimes, trait objects versus generics, Send and Sync, interior mutability, and error handling, and for each gives the answer in the three-part shape: the rule, a tiny example with real compiler output from Rust 1.99, and the reason. Use it to practice answering aloud.

What interviewers look for

A strong answer has the same structure every time. State the rule in one sentence. Show the smallest code that demonstrates it, ideally the failing version first. Explain what problem the rule prevents or what trade-off it makes. A weak answer recites a definition, hedges with "it depends" and stops. The correct use of "it depends" is to name the dependency: "it depends on whether the callee needs to own the value". Interviewers also listen for honesty about cost: Rust trades compile-time effort for run-time safety, and a candidate who can say where the cost lands sounds like someone who has shipped it.

Q1: What are the borrowing rules, and why do they exist?

At any moment a value can have any number of shared references (&T) or exactly one mutable reference (&mut T), never both, and a reference cannot outlive its owner. They exist to rule out data races and iterator invalidation at compile time. Show it with the vector example:

src/main.rsrust
fn main() {
    let mut items = vec![1, 2, 3];
    let first = &items[0];
    items.push(4);
    println!("first is {first}");
}
Text
error[E0502]: cannot borrow `items` as mutable because it is also borrowed as immutable
 --> e0502a.rs:4:5
  |
3 |     let first = &items[0];
  |                  ----- immutable borrow occurs here
4 |     items.push(4);
  |     ^^^^^^^^^^^^^ mutable borrow occurs here
5 |     println!("first is {first}");
  |                         ----- immutable borrow later used here

The push could reallocate the buffer, leaving first pointing at freed memory. The rule turns that use-after-free into a compile error. A good follow-up answer notes that borrows end at their last use, not at the end of the scope, which is why the program compiles if first is not used after the push.

Q2: What is a lifetime, and when do you have to write one?

A lifetime is the region of code in which a reference is valid, and an annotation like 'a tells the compiler how the lifetimes of inputs and outputs relate. You write one when the compiler cannot work out the relationship itself, most often in a function that returns a reference and takes more than one:

src/main.rsrust
fn longest(a: &str, b: &str) -> &str {
    if a.len() >= b.len() { a } else { b }
}
Text
error[E0106]: missing lifetime specifier
 --> i1.rs:1:33
  |
1 | fn longest(a: &str, b: &str) -> &str {
  |               ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
1 | fn longest<'a>(a: &'a str, b: &'a str) -> &'a str {

The compiler cannot tell whether the result borrows from a or from b, so it asks. Writing <'a> and tying all three to it says "the result is valid as long as both inputs are". The strong version of the answer adds that lifetimes do not extend how long data lives; they describe relationships the compiler then checks. The program with the fixed signature, run with an inner scope, prints inside: outer string and abc, and using result after the inner scope ends would be an error because result might point at the dropped inner.

Q3: What is the difference between String and &str?

String owns a growable heap buffer. &str is a borrowed view of UTF-8 bytes owned by someone else, a pointer and a length. Use &str in function parameters, since a &String coerces to it and literals are already &str. Use String when you need to own or modify the text. The follow-up trap is indexing: s[0] is not allowed on a str, because indexing bytes could split a multi-byte character; use .chars(), .char_indices() or .bytes() depending on what you mean.

Q4: Explain generics versus trait objects.

Generics are resolved at compile time. The compiler generates a copy of the function for each concrete type, which is fast and bloats the binary slightly. Trait objects, &dyn Trait or Box<dyn Trait>, are resolved at run time through a vtable: one copy of the function, one indirect call per method, and the ability to hold different types in one collection. Say which you would use and why: generics when the type is known at the call site, trait objects when the set of types is open or decided at run time. The measured costs are in static versus dynamic dispatch, where a mixed collection of trait objects took about 2.5 ns per call against 0.7 ns for an enum doing the same work. An interviewer who hears that you measured it will remember it.

Q5: What are Send and Sync?

Send means a value can be moved to another thread. Sync means a shared reference to it can be used from several threads, that is, &T is Send. Both are marker traits the compiler derives automatically, and a type loses them if any part lacks them. Rc<T> is neither, because its reference count is not atomic, so trying to send one across a thread boundary fails:

Text
error[E0277]: `Rc<Vec<i32>>` cannot be sent between threads safely
 --> e277.rs:6:32
  |
6 |       let handle = thread::spawn(move || {
  |                    ------------- ^------
  |
  = help: within `{[email protected]:6:32: 6:39}`, the trait `Send` is not implemented for `Rc<Vec<i32>>`

The fix is Arc, whose count is atomic. Mutation across threads adds Mutex, and this program increments a shared counter from four threads, 1,000 times each, and prints the right answer:

src/main.rsrust
use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0u32));
    let mut handles = Vec::new();
    for _ in 0..4 {
        let counter = Arc::clone(&counter);
        handles.push(thread::spawn(move || {
            for _ in 0..1000 {
                *counter.lock().unwrap() += 1;
            }
        }));
    }
    for h in handles {
        h.join().unwrap();
    }
    println!("total: {}", *counter.lock().unwrap());
}
Text
total: 4000

The point to make is that the data race, the classic concurrency bug, is not a rule to remember but a compile error. That is the claim Rust's concurrency story rests on.

Q6: What is interior mutability, and what does it cost?

Interior mutability lets you mutate through a shared reference by moving the borrow check from compile time to run time. Cell<T> copies values in and out, RefCell<T> hands out borrows and checks the rules when you ask, and Mutex<T> does the same across threads. The cost is that violations become panics instead of compile errors:

src/main.rsrust
use std::cell::RefCell;
use std::rc::Rc;

fn main() {
    let shared = Rc::new(RefCell::new(vec![1, 2, 3]));
    let a = Rc::clone(&shared);
    println!("owners: {}", Rc::strong_count(&shared));

    let first = a.borrow();
    println!("first element {}", first[0]);
    let mut writer = shared.borrow_mut(); // the borrow rules, checked at run time
    writer.push(4);
}
Text
owners: 2
first element 1

thread 'main' panicked at i3.rs:11:29:
RefCell already borrowed

The program takes a shared borrow with a.borrow(), keeps it alive, and then asks for a mutable one. The compile succeeds and the run panics with "RefCell already borrowed". That contrast is the answer to "when would you use it": when ownership genuinely cannot be arranged statically, as in a graph, and with the understanding that you have traded a compile-time guarantee for a run-time check.

Q7: How does error handling work, and when is panic! acceptable?

Recoverable failures return Result<T, E> and callers handle them with match, ? or combinators. panic! is for bugs, states that should be impossible, where continuing is worse than stopping: an index out of range, a violated invariant. unwrap and expect are panics in disguise; expect with a message that states why the case cannot happen is acceptable in code where it truly cannot, and a smell in code that handles user input. A library returns errors, defines its own error type with thiserror, and leaves the decision to the caller; an application can use anyhow to collect them. Mention that ? converts errors through From, which is how a function that reads a file and parses a number can return one error type.

Q8: What does unsafe actually mean?

It means you take over a promise the compiler cannot check. It unlocks five things: dereferencing raw pointers, calling unsafe functions, accessing mutable statics, implementing unsafe traits and reading union fields. It does not turn off the borrow checker. Good answers add the discipline: keep unsafe blocks tiny, wrap them in a safe API that makes misuse impossible, write a SAFETY comment, and run Miri. The full treatment is in unsafe Rust explained.

Questions to ask back

An interview is two-way, and good questions show you have worked with Rust at scale. Ask how the team handles errors across crate boundaries, whether they use anyhow or typed errors in libraries, what the policy is on unsafe and unwrap, how long a clean build takes and what they do about it, and how they pin the toolchain. Those questions reveal whether the codebase has the discipline the language makes possible.

Practicing

Take each question above and answer it aloud in under a minute without looking: rule, example, reason. Then break the example on purpose and read the compiler's message, because the ability to interpret an error message is the most visible sign of experience. The ownership concepts behind Q1, Q2 and Q3 are developed in ownership in Rust explained and the common errors in E0382, E0499 and E0597.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.