Brainbotox · Lessons · Exams

Rust Interview Questions, Advanced: Send and Sync, Async, Unsafe (30 questions)

by lazizanie · Programming · Rust · English

30 advanced Rust interview questions for senior developers with model answers: async and Pin, Send and Sync, atomics, variance, trait objects, unsafe, FFI, macros and performance.

Take this exam on Brainbotox, with marking →

30 questions. The model answers are folded under each one.

Question 1

Q1. Send and Sync. This code does not compile.

use std::{cell::RefCell, rc::Rc, thread};
let counter = Rc::new(RefCell::new(0));
let handles: Vec<_> = (0..4).map(|_| {
    let c = Rc::clone(&counter);
    thread::spawn(move || {
        *c.borrow_mut() += 1;
    })
}).collect();

(a) Define Send and Sync.

(b) Explain exactly why the compiler rejects this code.

(c) Rewrite it correctly.

Model answer

(a) Definitions

  • T: Send: a value of type T can be moved to another thread.
  • T: Sync: a &T can be shared between threads. Formally, T is Sync when &T is Send.

Both are marker traits that the compiler derives automatically: a type has them when all its fields have them.

(b) Why it fails. thread::spawn requires its closure to be Send, and the closure owns an Rc<RefCell<i32>>.

  • Rc is not Send: its reference count is a plain integer, not atomic. Two threads cloning or dropping it at once would corrupt the count, leading to a double free or a leak.
  • RefCell is not Sync: its borrow flag is not thread-safe either.

So the data race is refused at compile time, not found in production.

(c) Correct version: atomic reference count plus a lock.

use std::sync::{Arc, Mutex};
use std::thread;
let counter = Arc::new(Mutex::new(0));
let handles: Vec<_> = (0..4).map(|_| {
    let c = Arc::clone(&counter);
    thread::spawn(move || {
        *c.lock().unwrap() += 1;
    })
}).collect();
for h in handles { h.join().unwrap(); }
assert_eq!(*counter.lock().unwrap(), 4);
What a strong candidate adds: for a plain counter, Arc<AtomicI32> with fetch_add avoids the lock. std::thread::scope lets threads borrow from the stack without Arc at all.

Revise: Advanced Rust: Async, Unsafe, Macros and Performance

Question 2

Q2. Async code review. This handler runs on a multi-threaded Tokio runtime. state is an Arc<std::sync::Mutex<State>>.

async fn handle(state: Arc<Mutex<State>>) {
    let mut s = state.lock().unwrap();
    s.count += 1;
    save(s.count).await;
    std::thread::sleep(Duration::from_secs(1));
}

(a) Find the two problems and explain the consequence of each.

(b) Rewrite the function.

(c) What happens if you call handle(state) and never .await it?

Model answer

(a) Two problems

1. A std mutex guard is held across .await.

  • std::sync::MutexGuard is not Send, so the future is not Send and tokio::spawn(handle(..)) does not compile.
  • Even on a single-threaded runtime it is dangerous: the task is suspended at save(..).await while still holding the lock. Another task on the same thread that calls lock() blocks the thread, so the first task can never resume to release it: deadlock.

2. std::thread::sleep blocks a runtime worker thread. Async tasks share a small pool of threads and must give control back at each .await. A blocking call freezes that worker for a full second, and every other task scheduled on it waits.

(b) Rewrite: keep the lock for the shortest time, with no await inside, and sleep asynchronously.

async fn handle(state: Arc<Mutex<State>>) {
    let count = {
        let mut s = state.lock().unwrap();
        s.count += 1;
        s.count
    }; // guard dropped here
    save(count).await;
    tokio::time::sleep(Duration::from_secs(1)).await;
}

If the lock really must be held across an await, use tokio::sync::Mutex, whose lock().await suspends the task without blocking the thread. For CPU-heavy or blocking work, use tokio::task::spawn_blocking.

(c) Nothing runs. Rust futures are lazy: calling an async function only builds a state machine. It makes progress only when polled, by .await or by a runtime after spawn. The compiler warns that the future is unused.

Revise: Advanced Rust: Async, Unsafe, Macros and Performance

Question 3

Q3. Unsafe Rust.

(a) What exactly does an unsafe block allow that safe Rust does not?

(b) True or false: inside unsafe, the borrow checker is turned off. Explain.

(c) You must write a function that uses unsafe internally but is safe to call. What makes such an abstraction sound, and how do you check it?

Model answer

(a) Five extra abilities, and only these:

  1. Dereference a raw pointer.
  2. Call an unsafe function or method, including foreign (FFI) functions.
  3. Read or write a mutable static variable.
  4. Implement an unsafe trait, such as Send or Sync by hand.
  5. Read a field of a union.

(b) False. unsafe turns off nothing. References are still borrow-checked, types are still checked, and bounds checks still happen on normal indexing. It only unlocks the five abilities above, and moves the responsibility for their rules from the compiler to you. Breaking those rules is undefined behaviour, even inside unsafe.

(c) A sound safe wrapper

  • Soundness: no call made from safe code, with any arguments, can cause undefined behaviour. The function checks or guarantees every condition the unsafe code needs.
  • Keep the unsafe part small and private. Its invariants are protected by the module boundary, because any safe code in the same module can break them.
  • Document each block with a // SAFETY: comment saying why the conditions hold.
pub fn first_two(v: &[u8]) -> Option<(u8, u8)> {
    if v.len() < 2 {
        return None;
    }
    // SAFETY: the length was checked above,
    // so indexes 0 and 1 are in bounds.
    unsafe {
        Some((*v.get_unchecked(0), *v.get_unchecked(1)))
    }
}

Checking it: run the tests under cargo miri test, which detects many kinds of undefined behaviour; use sanitizers and fuzzing for FFI code; and prove with a benchmark that the unsafe version is worth having at all.

Revise: Advanced Rust: Async, Unsafe, Macros and Performance

Question 4

Q4. Pin. What problem does Pin solve, and why do futures need it? What is Unpin?

Model answer

An async block compiles to a state machine that stores its local variables. If one local is a reference to another local, the future is self-referential: it holds a pointer into itself.

Moving such a value copies its bytes to a new address, but the internal pointer still points to the old address. That would be a dangling pointer.

Pin<P> wraps a pointer and guarantees the value it points to will not be moved again. Future::poll takes self: Pin<&mut Self>, so once a future has been polled, and may have created internal references, it can never move.

Unpin is an auto trait meaning: moving this type is always fine, even when pinned. Almost every ordinary type is Unpin. Futures made by async are not.

In practice:

let fut = Box::pin(async { /* ... */ });     // pinned on the heap
let fut = std::pin::pin!(async { /* ... */ }); // pinned on the stack
tokio::pin!(fut);   // needed before polling it in a select! loop

.await pins for you, so most code never mentions Pin. You meet it when storing futures, writing a Future or Stream by hand, or polling a future more than once across loop iterations.

Question 5

Q5. How futures run. Describe the Future trait. What do Poll::Pending and the Waker do, and what is the role of the executor?

Model answer
pub trait Future {
    type Output;
    fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>)
        -> Poll<Self::Output>;
}

A future is a value that can be polled. Each call to poll runs it as far as it can go without blocking:

  • Poll::Ready(value): finished.
  • Poll::Pending: cannot continue yet, for example the socket has no data.

Before returning Pending, the future must store the Waker from the context somewhere that will learn when progress is possible (the I/O driver, a timer, a channel). When the event happens, that component calls waker.wake().

The executor (Tokio, async-std, smol) owns the tasks. It polls a task, and if it gets Pending it sets the task aside and runs others. When the waker fires, the task goes back on the run queue and is polled again.

Key properties:

  • Futures are inert: nothing happens until something polls them.
  • There is no busy-waiting: a task is polled only after a wake-up.
  • The standard library defines the trait, but ships no executor. You choose a runtime.
  • A future that returns Pending without arranging a wake-up hangs for ever.

Question 6

Q6. Async state machines. What does the compiler generate for an async fn? Why does this recursive function not compile, and how do you fix it?

async fn countdown(n: u32) {
    if n > 0 {
        countdown(n - 1).await;
    }
}
Model answer

An async fn becomes an ordinary function that returns an anonymous type implementing Future. That type is an enum-like state machine: one state per .await point, and each state stores the local variables that are still alive across that await.

Consequences:

  • The future's size is known at compile time: roughly the size of its largest state.
  • It lives wherever you put it. No heap allocation is needed, which is why Rust async is cheap.
  • A large local kept across an .await makes the whole future large.

The recursion fails for the same reason a recursive enum does: the future for countdown would contain the future for countdown, which contains another, so the size is infinite.

Fix: put the inner future behind a pointer, which has a known size.

async fn countdown(n: u32) {
    if n > 0 {
        Box::pin(countdown(n - 1)).await;
    }
}

The cost is one heap allocation per level of recursion. Often the better answer is to write the loop iteratively.

Question 7

Q7. Spawning tasks. Why does this not compile, and what are two ways to fix it?

async fn run(names: Vec<String>) {
    let prefix = String::from("hello");
    for name in &names {
        tokio::spawn(async {
            println!("{} {}", prefix, name);
        });
    }
}
Model answer

tokio::spawn requires its future to be Send + 'static.

  • 'static: the task runs independently and may outlive run. It must not borrow anything from run's stack. Here the async block borrows prefix and name, both of which die when run returns.
  • Send: on a multi-threaded runtime the task may be moved between worker threads at any .await.

Fix 1: give each task its own data with move and clones (or an Arc for something large).

let prefix = std::sync::Arc::new(prefix);
for name in names {                       // take ownership of each name
    let prefix = prefix.clone();
    tokio::spawn(async move {
        println!("{} {}", prefix, name);
    });
}

Fix 2: do not spawn. If the work only needs to run concurrently inside this function, join the futures. They can borrow locals because they cannot outlive the function.

let prefix = &prefix;                     // a shared reference is Copy
let jobs = names.iter().map(|name| async move {
    println!("{} {}", prefix, name);
});
futures::future::join_all(jobs).await;

Here async move moves only the two references into each future, not the strings themselves.

Also keep the JoinHandle and await it if you need the result or want to know that a task panicked.

Question 8

Q8. Cancellation. How is an async task cancelled in Rust? What does "cancellation safe" mean in a tokio::select!, and what can go wrong here?

loop {
    tokio::select! {
        res = socket.read_exact(&mut buf) => handle(res, &buf),
        _ = interval.tick() => send_heartbeat().await,
    }
}
Model answer

A future is cancelled simply by dropping it. It stops at whatever .await it had reached and never runs again. Its local variables are dropped, so destructors run, but no code after that await executes.

select! polls all branches. When one completes, the others are dropped, which cancels them.

A future is cancellation safe if dropping it before completion loses nothing: restarting it later behaves the same.

The bug: read_exact is not cancellation safe. Suppose it has read 60 of 100 bytes when the timer fires. The read future is dropped, and those 60 bytes are gone: consumed from the socket, but the count of how much was read lived inside the dropped future. The next iteration starts a new read at the wrong place in the stream. The protocol is now out of step.

Fixes:

  • Use a cancellation-safe operation in the select!, such as read into a buffer you own outside the loop, and track progress yourself.
  • Create the future once, outside the loop, pin it, and poll it by reference (&mut fut), so it is resumed instead of recreated.
  • Move the reading into its own task and send complete messages over a channel. mpsc::Receiver::recv is cancellation safe.

Question 9

Q9. Backpressure. A task reads messages from a socket and sends them to a worker task that is slower. What is the difference between an unbounded and a bounded channel here?

Model answer
  • Unbounded channel: send never waits. If the producer is faster than the consumer, messages pile up in memory. Under sustained load the process grows until it is killed. Latency also grows without limit, because each message waits behind an ever longer queue.
  • Bounded channel: it has a capacity. When it is full, send(...).await suspends the producer until there is room. The producer therefore stops reading from the socket, the kernel's receive buffer fills, and TCP flow control slows the remote sender. The slowness propagates back to the source. This is backpressure.
let (tx, mut rx) = tokio::sync::mpsc::channel::<Msg>(100);
// producer
tx.send(msg).await?;          // waits when 100 are queued
// consumer
while let Some(msg) = rx.recv().await {
    process(msg).await;
}

The capacity is a design decision: it bounds memory and the worst-case queueing delay.

When waiting is not acceptable, decide explicitly what to drop: try_send returns an error when full, so you can discard the message, count it, or reject the request. That is load shedding. An unbounded queue only hides the decision until the process fails.

Question 10

Q10. Choosing a sharing primitive. Several threads need access to shared data. When do you choose Arc<Mutex<T>>, Arc<RwLock<T>>, an atomic, or a channel?

Model answer

First, Arc only provides shared ownership across threads. What goes inside decides how the data may be modified.

  • Atomic (AtomicUsize, AtomicBool): a single number or flag. Lock-free and the cheapest. Counters, flags, ids.
  • Mutex<T>: the default for shared mutable state. One thread at a time. Simple, and fast when the critical section is short.
  • RwLock<T>: many readers or one writer. Worth it when reads greatly outnumber writes and hold the lock long enough to matter. For very short sections it is often slower than a mutex, and writers can be starved depending on the implementation.
  • Channel: no shared state at all. One thread owns the data, and the others send it messages. Best when work flows in one direction, or when the logic is easier to follow as a single owner processing requests.

Other tools worth naming:

  • For read-mostly data that is replaced as a whole (configuration), swap an Arc<T> snapshot (the arc-swap crate) so readers never block.
  • A concurrent map such as DashMap when one big lock around a HashMap is the bottleneck.

In all cases the compiler enforces the choice: data inside a Mutex can only be reached through the lock guard, so you cannot forget to lock.

Question 11

Q11. Mutex poisoning. Why does mutex.lock() return a Result? What is poisoning, and how should you handle it?

Model answer

If a thread panics while holding the lock, the data may have been left half-updated: an invariant may be broken. The standard library marks the mutex as poisoned, and every later lock() returns Err(PoisonError) to warn the other threads.

Handling it:

  • Propagate the failure: lock().unwrap(). If another thread panicked while changing shared state, panicking here too is usually the honest response. This is the common choice.
  • Recover when you know the data is still usable, or you can repair it:
let mut guard = match mutex.lock() {
    Ok(g) => g,
    Err(poisoned) => poisoned.into_inner(),   // take the guard anyway
};

Poisoning is a warning, not a safety mechanism: the data is still memory-safe, it may just be logically inconsistent.

Not every mutex does this. parking_lot::Mutex and tokio::sync::Mutex do not poison: their lock returns the guard directly.

Best practice is to make poisoning unlikely: keep critical sections short, and do not call code that may panic while holding a lock.

Question 12

Q12. Atomic orderings. What is the Ordering argument of atomic operations for? Explain Relaxed, Acquire/Release and SeqCst, and give a use for each.

Model answer

Every atomic operation is indivisible, whatever the ordering. The Ordering says what else the operation guarantees about the order in which other threads see memory effects. Weaker orderings let the CPU and compiler reorder more, and can be faster.

  • Relaxed: atomicity only. No guarantee about ordering relative to other variables. Right for a statistics counter or a simple id generator, where only the value itself matters.
HITS.fetch_add(1, Ordering::Relaxed);
  • Release (on store) and Acquire (on load): they create a happens-before link. Everything the writer did before a Release store is visible to a thread that later does an Acquire load of that value. This is what you need to publish data: write the data, then set a ready flag with Release; the reader checks the flag with Acquire and may then read the data. Locks and Arc's reference count are built on this.
  • SeqCst: the strongest. All SeqCst operations appear in one single order that every thread agrees on. Needed for the rare algorithms that involve several atomics and depend on that global order.

Practical advice: if you are not sure, use SeqCst. It is always correct, and only slightly slower on most hardware. Weaken it only with a clear argument, and test with tools such as loom.

Question 13

Q13. Interior mutability. What is interior mutability? Compare Cell, RefCell, Mutex and RwLock, and say what UnsafeCell has to do with them.

Model answer

Normally a shared reference &T is read-only. Interior mutability lets you change a value through a &T, with the exclusivity rule enforced by some other mechanism than the compile-time borrow checker.

TypeHow it stays safeThreads
Cell<T>No references to the inside: you only get (copy out) and set or replace. No run-time cost.Single thread
RefCell<T>Counts borrows at run time. Panics on a violation.Single thread
Mutex<T>Blocks other threads until the guard is dropped.Many
RwLock<T>Many readers or one writer, blocking.Many
AtomicsHardware atomic instructions.Many

UnsafeCell<T> is the one primitive underneath all of them. It is the only legal way to obtain a *mut T from a &UnsafeCell<T>. Mutating data behind a shared reference by any other route is undefined behaviour, because the compiler assumes data behind &T does not change. UnsafeCell switches that assumption off for its contents.

Typical uses: caching a computed value in a method that takes &self, counters, and shared state behind Rc or Arc.

Question 14

Q14. The limits of safety. Rust is called memory safe and free of data races. Name four kinds of bug that safe Rust does not prevent.

Model answer

Safe Rust guarantees: no use after free, no dangling references, no data races, no reading uninitialised memory, no buffer overruns. It does not guarantee a correct program.

Not prevented:

  • Deadlocks. Two threads taking two mutexes in opposite orders compile fine and hang. So does locking the same std mutex twice in one thread.
  • Memory leaks. Rc cycles, std::mem::forget, Box::leak, a collection that only grows. Leaking is considered safe.
  • Race conditions at the logical level. A check followed by an action as two separate locked steps, or operations arriving in an unexpected order. Only data races are ruled out.
  • Panics. Indexing out of bounds, unwrap() on None, division by zero, a RefCell borrowed twice.
  • Integer overflow. It panics in debug builds and wraps silently in release builds by default. Use checked_add, saturating_add or wrapping_add to state the intent.
  • Logic errors, and resource exhaustion such as unbounded queues or stack overflow from deep recursion.

And all guarantees assume that every unsafe block in the program and its dependencies is correct.

Question 15

Q15. Variance. What is variance? Why is &'a T covariant in T while &'a mut T is invariant in T?

Model answer

Variance describes how subtyping of a parameter carries over to the whole type. In Rust the only subtyping is between lifetimes: 'long is a subtype of 'short, because a reference that lives longer can be used wherever a shorter one is expected.

  • Covariant: a longer lifetime inside is accepted where a shorter one is expected. &'a T, Box<T>, Vec<T> are covariant in T.
  • Invariant: the type must match exactly. &mut T, Cell<T>, RefCell<T>, Mutex<T> are invariant in T.
  • Contravariant: the reverse direction. Only function arguments: fn(T) is contravariant in T.

Why &mut T must be invariant: through a &mut you can write. If shortening were allowed, this would compile:

fn overwrite<'a>(slot: &mut &'a str, value: &'a str) {
    *slot = value;
}
let mut long: &'static str = "static";
{
    let local = String::from("temporary");
    overwrite(&mut long, &local);   // rejected by invariance
}
println!("{}", long);               // would be a dangling reference

With a read-only &T nothing can be written back, so treating a long lifetime as a shorter one is harmless.

You meet variance when writing types with raw pointers: *const T is covariant, *mut T is invariant, and PhantomData is used to select the variance you need.

Question 16

Q16. Higher-ranked trait bounds. What does for<'a> mean in this signature, and why is it needed?

fn apply<F>(f: F) -> usize
where
    F: for<'a> Fn(&'a str) -> &'a str,
{
    let s = String::from("hello world");
    f(&s).len()
}
Model answer

for<'a> reads: for every possible lifetime 'a. The bound says that f must work with a string slice of any lifetime, and return a slice with that same lifetime. It is a higher-ranked trait bound (HRTB).

Why it is needed: the string s is created inside apply. Its lifetime does not exist from the caller's point of view, so the caller cannot name it.

If the lifetime were an ordinary generic parameter of apply:

fn apply<'a, F>(f: F) -> usize where F: Fn(&'a str) -> &'a str

then the caller would choose 'a, and it would have to outlive the call. A local variable of apply cannot satisfy that, so f(&s) would not compile.

With for<'a>, the callee picks the lifetime at each call.

You rarely write it, because lifetime elision in Fn bounds inserts it for you:

F: Fn(&str) -> &str     // means for<'a> Fn(&'a str) -> &'a str

You need the explicit form when elision is not enough, for example with a trait that has its own lifetime parameter: T: for<'de> Deserialize<'de>, which is what DeserializeOwned means.

Question 17

Q17. Dyn compatibility. Why can this trait not be used as dyn Shape? State the rules and show how to keep the trait usable as a trait object.

trait Shape {
    fn area(&self) -> f64;
    fn scaled(&self, k: f64) -> Self;
    fn draw<C: Canvas>(&self, canvas: &mut C);
}
Model answer

A trait object calls methods through a vtable, a table of function pointers built for each concrete type. The caller does not know the concrete type or its size. A trait is dyn compatible (formerly "object safe") only if every method can work under those conditions.

Two methods break it:

  • scaled returns Self. Through dyn Shape, the caller does not know what type or size comes back.
  • draw is generic. There would be one version per type C, an unbounded number, so it cannot be a single vtable entry.

Main rules for a dyn-compatible trait:

  • no method returns Self or takes Self by value as another parameter;
  • no method has generic type parameters;
  • every method has a receiver (&self, &mut self, Box<Self>...);
  • the trait does not require Self: Sized, and has no associated constants.

Keeping it usable: exclude the offending methods from the vtable with where Self: Sized, or change their signature.

trait Shape {
    fn area(&self) -> f64;
    fn scaled(&self, k: f64) -> Self
    where
        Self: Sized;                       // not callable on dyn Shape
    fn draw(&self, canvas: &mut dyn Canvas);   // dynamic, not generic
    fn boxed_scaled(&self, k: f64) -> Box<dyn Shape>;
}

Question 18

Q18. Associated types and generic parameters. Why is Iterator defined with an associated type (type Item) while From<T> uses a generic parameter? How do you choose?

Model answer

The question to ask: for one implementing type, can there be several implementations, or exactly one?

  • Generic parameter: the trait can be implemented many times for the same type, once per choice of the parameter. A String can be built from several things:
impl From<&str> for String { ... }
impl From<char> for String { ... }
impl From<Box<str>> for String { ... }

The caller selects which one, often by inference.

  • Associated type: the type is determined by the implementation. There is one answer per implementing type. A given iterator yields one kind of item:
impl Iterator for Lines {
    type Item = String;
    fn next(&mut self) -> Option<String> { ... }
}

Why it matters:

  • With an associated type, code that uses the trait is simpler: fn sum<I: Iterator<Item = i32>>(it: I). If Item were a generic parameter, every function would need an extra type parameter, and it.next() would be ambiguous if a type implemented Iterator<u8> and Iterator<char>.
  • The compiler can infer the associated type from the implementing type, because it is unique.

A trait can use both: Add<Rhs> has a generic right-hand side (you can add several types to a Point) and an associated Output (each combination gives one result type).

Question 19

Q19. The orphan rule. You want to implement Display for Vec<String> and the compiler refuses. What is the rule, why does it exist, and what is the standard way around it?

Model answer

The orphan rule: you may implement a trait for a type only if the trait or the type is defined in your crate.

Display belongs to the standard library, and so does Vec. Neither is yours, so the implementation is rejected.

Why: coherence. For any type and trait there must be at most one implementation in the whole program. If any crate could implement any trait for any type, two dependencies could both provide Display for Vec<String>, and your program would stop compiling, or the meaning would depend on which one was linked. The rule also lets a library add an implementation later without breaking its users.

The workaround: the newtype pattern. Wrap the foreign type in a tuple struct of your own. The wrapper is local, so you can implement anything for it.

use std::fmt;
struct Names(Vec<String>);
impl fmt::Display for Names {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "[{}]", self.0.join(", "))
    }
}

The wrapper has no run-time cost. Its drawback is that it does not have the inner type's methods: expose what you need, implement Deref with care, or reach in with .0.

Newtypes are also used for type safety: struct UserId(u64) and struct OrderId(u64) cannot be mixed up.

Question 20

Q20. Zero-cost abstractions. What does "zero-cost abstraction" mean in Rust? Is there any cost to heavy use of generics?

Model answer

It means two things: you do not pay for features you do not use, and what you do use compiles to code as fast as the equivalent written by hand.

Examples:

  • An iterator chain such as v.iter().filter(..).map(..).sum() is compiled into a single loop, with no intermediate collections and often no bounds checks.
  • Option<Box<T>> and Option<&T> are the size of one pointer: None is represented by the null value.
  • A newtype such as struct Meters(f64) has exactly the layout of an f64.
  • Generic functions are monomorphised: one specialised copy per concrete type, with calls resolved statically and inlined.

The cost is real, but it is paid at build time, not at run time:

  • Longer compile times. Each instantiation is type-checked once but optimised and code-generated separately.
  • Larger binaries (code bloat), which can also hurt the instruction cache.

Ways to limit it:

  • Use dyn Trait where the call is not performance-critical: one copy of the code.
  • Keep the generic part thin: a small generic wrapper that converts its argument and calls a non-generic inner function.
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<File> {
    fn inner(path: &Path) -> io::Result<File> { /* all the work */ }
    inner(path.as_ref())
}

Question 21

Q21. Sized. What is a dynamically sized type? What do the Sized trait and the ?Sized bound mean, and what is a fat pointer?

Model answer

Most types have a size known at compile time: they are Sized. A dynamically sized type (DST) does not:

  • str and [T]: the length is only known at run time;
  • dyn Trait: the concrete type behind it is only known at run time.

A DST cannot be a local variable, a parameter or a return value, because the compiler would not know how much stack space to reserve. It is always used behind a pointer: &str, &[T], Box<dyn Trait>, Arc<str>.

That pointer is a fat pointer, two words wide:

  • for a slice or str: the address and the length;
  • for a trait object: the address and a pointer to the vtable.

Every generic parameter has an implicit T: Sized bound. ?Sized removes it, meaning "T may or may not be sized":

fn show<T: Display + ?Sized>(value: &T) {
    println!("{}", value);
}
show("a str");        // T = str, allowed thanks to ?Sized
show(&42);            // T = i32

With ?Sized, the function may only use T behind a pointer. This is why Box<T>, Rc<T> and &T are declared with T: ?Sized.

Question 22

Q22. PhantomData. What is PhantomData<T>? Give two situations where you need it.

Model answer

PhantomData<T> is a zero-sized marker. It tells the compiler: treat this struct as if it contained a T, although no T is stored. It takes no space at run time.

The compiler rejects a type or lifetime parameter that is not used in any field. PhantomData uses it, and at the same time declares how the struct relates to it: ownership, lifetime, variance and auto traits.

1. Typed identifiers and type-state. The parameter exists only for the type checker.

use std::marker::PhantomData;
struct Id<T> {
    raw: u64,
    _kind: PhantomData<T>,
}
fn load_user(id: Id<User>) { ... }
// passing an Id<Order> is a compile error

The same technique encodes states: Connection<Open> and Connection<Closed>, where only the open one has a send method.

2. Raw pointers in unsafe abstractions. A raw pointer carries no lifetime and no ownership information, so you must supply it.

struct Iter<'a, T> {
    ptr: *const T,
    end: *const T,
    _marker: PhantomData<&'a T>,   // behaves like a borrow of T for 'a
}

Now the borrow checker keeps the original collection borrowed for 'a. Writing PhantomData<T> instead would say the struct owns a T, which affects drop checking. Choosing the right phantom type also sets variance and whether the struct is Send and Sync.

Question 23

Q23. Aliasing in unsafe code. This program compiles and may even print 7. Is it correct? Explain.

let mut x = 5;
let p = &mut x as *mut i32;
let a = unsafe { &mut *p };
let b = unsafe { &mut *p };
*a += 1;
*b += 1;
println!("{}", x);
Model answer

No. It is undefined behaviour.

The rules for references hold everywhere, including in unsafe code: a &mut T must be the only active way to reach its data for as long as it is in use. Here a and b are two live mutable references to the same i32. Creating b while a is still used afterwards breaks the rule, even though the code "works".

Why it matters: the compiler optimises on that assumption. It tells LLVM that the two references do not alias, so it may keep *a in a register, reorder the writes, or drop one. The result can change with the optimisation level or the compiler version.

unsafe does not relax the rules. It only lets you perform operations the compiler cannot check, and makes you responsible for upholding them.

Correct versions:

// stay with raw pointers: they are allowed to alias
unsafe {
    *p += 1;
    *p += 1;
}
// or use one reference at a time
let a = unsafe { &mut *p };
*a += 1;                       // last use of a
let b = unsafe { &mut *p };
*b += 1;

Miri detects this: cargo +nightly miri run reports the violation of the aliasing model (Stacked Borrows or Tree Borrows). Running tests under Miri is standard practice for any crate with unsafe code.

Question 24

Q24. FFI. You need to call a C function int process(const char *name, Point p) from Rust. What do you have to get right? Find the bug in this call.

let ptr = CString::new("job").unwrap().as_ptr();
unsafe { process(ptr, point) };
Model answer

Declaring and calling it:

use std::ffi::{c_char, c_int, CString};
#[repr(C)]
#[derive(Clone, Copy)]
pub struct Point { x: f64, y: f64 }
unsafe extern "C" {
    fn process(name: *const c_char, p: Point) -> c_int;
}
let name = CString::new("job").unwrap();   // keep it alive
let rc = unsafe { process(name.as_ptr(), point) };

What to get right:

  • Layout: #[repr(C)] on every struct that crosses the boundary. Rust's default layout is unspecified and may reorder fields.
  • Types: use c_int, c_char and friends, not guesses about widths.
  • Strings: C strings end with a zero byte and are not necessarily UTF-8. Use CString to pass one, CStr to read one. A Rust &str has no terminator.
  • Ownership: agree on who frees what. Memory allocated by one side must be freed by that side's allocator.
  • Panics: a Rust panic must not unwind into C. In a function exported to C, catch it with std::panic::catch_unwind or let it abort.
  • The declaration is a promise the compiler cannot check, so the call is unsafe. (unsafe extern is the form required by the 2024 edition.)

The bug: CString::new("job").unwrap() is a temporary. It is dropped at the end of that statement, so ptr points to freed memory before process is called. Bind the CString to a variable that outlives the call. The compiler warns about this pattern.

Question 25

Q25. Macros. What is the difference between declarative macros (macro_rules!) and procedural macros? Name the three kinds of procedural macro and explain what hygiene means.

Model answer

Macros generate code at compile time. They take syntax as input, so they can do what functions cannot: accept a variable number of arguments, create new items, or implement traits.

Declarative macros (macro_rules!) work by pattern matching on token trees and substituting into a template.

macro_rules! square {
    ($x:expr) => { $x * $x };
}
let n = square!(3 + 1);   // 16: the expression is kept as one unit

They are defined in ordinary code, compile quickly, and suit repetition and small DSLs. vec! and println! are of this kind.

Procedural macros are Rust functions that receive a token stream and return a token stream. They live in a separate crate of type proc-macro, usually use the syn and quote crates, and can run arbitrary logic. Three kinds:

  • Derive: #[derive(Serialize)] adds an implementation next to a struct or enum.
  • Attribute: #[tokio::main], #[get("/users")] transforms the item it is attached to.
  • Function-like: sqlx::query!("SELECT ...") looks like a call and can validate its input at compile time.

Their cost is build time, and errors that are harder to read.

Hygiene: identifiers created inside a macro_rules! macro live in their own scope. A local variable named tmp in the macro body cannot clash with, or capture, a tmp at the call site. Procedural macros are only partly hygienic, so they should use full paths such as ::std::option::Option.

Question 26

Q26. Uninitialised memory. Why is reading an uninitialised value undefined behaviour even for an integer? What is MaybeUninit<T> for? Show how to fill a buffer without initialising it first.

Model answer

The compiler assumes every value of a type is valid for that type. A bool is 0 or 1, a reference is non-null and aligned, an enum has a valid tag. Uninitialised memory has no defined content, and the optimiser may treat it as any value, different at each read. So producing an uninitialised bool, reference or even integer is undefined behaviour, not just "some random number".

This is why the old std::mem::uninitialized() is deprecated: almost every use was undefined behaviour.

MaybeUninit<T> is a wrapper that may or may not hold a valid T. The compiler makes no assumption about its content, and does not drop it. You write into it, then declare it initialised.

use std::mem::MaybeUninit;
let mut buf = [MaybeUninit::<u8>::uninit(); 64];
for (i, slot) in buf.iter_mut().enumerate() {
    slot.write(i as u8);                 // safe: writing never reads
}
// SAFETY: all 64 elements were written above.
let buf: [u8; 64] = unsafe {
    std::mem::transmute::<_, [u8; 64]>(buf)
};

Rules: call assume_init() (or equivalent) only when every byte of the value has really been written. Doing it early is undefined behaviour.

Uses: large buffers handed to a reader, out-parameters of C functions, and building arrays element by element. In most code, initialising with zeros is fast enough and far safer.

Question 27

Q27. Moving out of a mutable reference. This does not compile. Why, and how do you fix it without cloning the string?

enum State {
    Draft(String),
    Published(String),
}
fn publish(s: &mut State) {
    if let State::Draft(text) = *s {
        *s = State::Published(text);
    }
}
Model answer

Error: cannot move out of *s which is behind a mutable reference.

The pattern tries to move the String out of the value that s points to. That would leave *s without a valid value for a moment. If anything panicked in between, the caller would be holding a broken State. A reference must always point to a valid value, so the compiler forbids it.

The solution is to swap in a valid replacement and take the old value out in one step.

With std::mem::take, on the inner string (it leaves an empty String behind, which costs no allocation):

fn publish(s: &mut State) {
    if let State::Draft(text) = s {
        let text = std::mem::take(text);
        *s = State::Published(text);
    }
}

With std::mem::replace, on the whole value, when you want to match by value:

fn publish(s: &mut State) {
    let old = std::mem::replace(s, State::Draft(String::new()));
    *s = match old {
        State::Draft(text) => State::Published(text),
        other => other,
    };
}
  • mem::take(x) replaces *x with Default::default() and returns the old value.
  • mem::replace(x, v) does the same with a value you supply.
  • Option::take() is the same idea for an Option, leaving None.

These are the standard tools for state machines and for taking ownership of a field in Drop or through &mut self.

Question 28

Q28. Performance work. A Rust service is slower than expected. Describe how you would investigate, and list the build settings and code-level changes that most often help.

Model answer

1. Check the basics. Is it built with --release? A debug build can be 10 to 100 times slower.

2. Measure.

  • Profile the real workload: perf with cargo flamegraph, or samply. Keep debug symbols in release: debug = true in the profile.
  • Benchmark a specific function with criterion, which handles warm-up and statistical noise.
  • Look at allocations with a heap profiler (dhat, heaptrack).

3. Build settings in Cargo.toml:

[profile.release]
opt-level = 3
lto = "fat"          # or "thin": optimise across crates
codegen-units = 1    # better optimisation, slower build
panic = "abort"      # smaller, slightly faster, no unwinding

Also consider -C target-cpu=native when you control the hardware, and profile-guided optimisation.

4. Code-level changes that usually matter most:

  • Fewer allocations: remove needless .clone() and .to_string(), pass &str and &[T], use Vec::with_capacity, reuse buffers across iterations.
  • The right data structure and algorithm, before any micro-tuning.
  • A faster hasher for HashMap when keys are trusted: the default (SipHash) resists denial-of-service attacks but is slower than ahash or FxHash.
  • Iterators instead of indexing, which lets the compiler drop bounds checks.
  • Buffered I/O: BufReader, BufWriter, and locking stdout once.
  • In async code: no blocking calls on the runtime, and fewer locks held across awaits.

Change one thing at a time and measure again.

Question 29

Q29. Cow. What is Cow<'a, str>? Write a function that replaces spaces with underscores but allocates only when the input actually contains a space.

Model answer

Cow means clone on write. It is an enum that holds either borrowed or owned data:

pub enum Cow<'a, B: ToOwned + ?Sized> {
    Borrowed(&'a B),
    Owned(B::Owned),
}

So Cow<'a, str> is either a &'a str or a String. It dereferences to &str in both cases, so callers use it like a string.

use std::borrow::Cow;
fn underscored(input: &str) -> Cow<'_, str> {
    if input.contains(' ') {
        Cow::Owned(input.replace(' ', "_"))   // must allocate
    } else {
        Cow::Borrowed(input)                  // no allocation
    }
}
let a = underscored("hello");        // borrowed
let b = underscored("hello world");  // owned
println!("{} {}", a, b);

The point: the common case costs nothing, and the function has one return type for both paths. Without Cow, it would have to return a String and allocate every time.

Other uses:

  • String::from_utf8_lossy returns a Cow<str>: borrowed if the bytes were already valid UTF-8.
  • A config struct that holds either a static default or a loaded value: Cow<'static, str>.
  • to_mut() gives a &mut to the owned form, cloning first only if it was borrowed. into_owned() gives the owned value.

Cost: one branch on each access, and a slightly more complex type in your API. Use it where avoiding the allocation is measurable.

Question 30

Q30. Const generics. What are const generics? Define a Matrix type whose dimensions are checked at compile time, with a transpose method.

Model answer

Const generics let a type or function be generic over a constant value, not only over a type. The value becomes part of the type.

#[derive(Debug, Clone, Copy)]
struct Matrix<const R: usize, const C: usize> {
    data: [[f64; C]; R],
}
impl<const R: usize, const C: usize> Matrix<R, C> {
    fn transpose(&self) -> Matrix<C, R> {
        let mut out = [[0.0; R]; C];
        for r in 0..R {
            for c in 0..C {
                out[c][r] = self.data[r][c];
            }
        }
        Matrix { data: out }
    }
}
fn multiply<const R: usize, const K: usize, const C: usize>(
    a: &Matrix<R, K>,
    b: &Matrix<K, C>,
) -> Matrix<R, C> { /* ... */ }

What you gain:

  • Dimension errors are compile errors. Multiplying a 2x3 by a 2x3 does not type-check, because the inner dimension K must match.
  • No heap allocation: the data is a plain array of known size.
  • No run-time size checks, and loops with constant bounds that the compiler can unroll and vectorise.

They are also why the standard library can implement traits for arrays of any length (impl<T, const N: usize> ... for [T; N]), where it used to stop at 32.

Current limits on stable Rust: the parameter must be an integer type, bool or char, and you cannot use expressions that compute with a const parameter in a type, such as [T; N + 1].