Rust Interview Questions
Q: What is the borrow checker and why does Rust have it?
The borrow checker enforces ownership rules at compile time, preventing: use-after-free (using memory after it's freed), dangling pointers (pointers to freed memory), data races (concurrent mutable access). These are the root causes of most memory safety bugs in C/C++. Rust catches them at compile time with zero runtime cost — no garbage collector needed.
Q: What is the difference between String and &str?
String is an owned, heap-allocated, mutable, growable UTF-8 string. &str is a borrowed string slice — a reference to string data stored somewhere (heap, stack, or binary). &str is always immutable. Function parameters should typically accept &str (more flexible — accepts both &String and string literals). Use String when you need to own or modify the string.
Q: What is the difference between Box<T>, Rc<T>, and Arc<T>?
Box<T> — single owner, heap allocation; used for recursive types and dynamic dispatch (Box<dyn Trait>)
Rc<T> — reference-counted shared ownership, single-threaded only (not Send/Sync)
Arc<T> — atomic reference-counted, thread-safe shared ownership (used with Mutex/RwLock for shared mutable state)
Q: What is a lifetime and when do you need to specify one?
Lifetimes describe how long references are valid — they prevent dangling references. Usually inferred by the compiler (lifetime elision). You need explicit lifetime annotations when a function returns a reference and the compiler can't figure out which input reference it comes from: fn longest<'a>(x: &'a str, y: &'a str) -> &'a str.
Q: What is panic! vs Result in Rust?
panic! immediately terminates the thread (and optionally unwinds the stack) — use for unrecoverable errors (bugs, invariant violations). Result<T, E> is for recoverable errors that callers should handle — the idiomatic approach. Never use panic! in library code; always use Result. In application code, unwrap()/expect() are fine in prototypes but should be replaced with proper error handling.
Keep your own version of these notes — editable, searchable, and organised by your stack.
Start free