Top 10 Rust scenario questions
Try each one yourself first, then open the model answer.
1. The compiler says a value was used after it was moved. What are your options?
Show answerHide answer
Borrow it instead of moving, clone it if a second copy is truly needed, or restructure so ownership passes back. Choose based on who should own the data.
2. You need to modify a collection while holding a reference to one of its elements. Why is it rejected?
Show answerHide answer
Mutation could reallocate and invalidate the reference. Finish using the borrow first, copy out the data you need, or use indexes.
3. Several threads must update a shared counter. What would you use?
Show answerHide answer
Arc<Mutex<T>> for shared mutable state, or an atomic type for a simple counter. Channels are an alternative when you can pass messages instead.
4. A library function calls unwrap and crashes the user's program. How would you improve it?
Show answerHide answer
Return Result and use the ? operator to propagate errors. Reserve unwrap and expect for cases that indicate a programming bug.
5. The compiler asks for a lifetime annotation on a function returning a reference. What does it mean?
Show answerHide answer
It needs to know which input the returned reference borrows from. The annotation describes that relationship and does not extend how long anything lives.
6. You need a tree where children refer to their parent. How do you avoid reference cycles?
Show answerHide answer
Use Rc for children and Weak for the parent link, or store nodes in a vector and refer to them by index.
7. An async task holds a standard mutex guard across an await and the service stalls. What do you do?
Show answerHide answer
Drop the guard before awaiting, or use an async-aware mutex when the lock must be held across await points.
8. Different types must be stored in one list and used through shared behaviour. Which approach?
Show answerHide answer
Use trait objects such as Box<dyn Trait> for an open set of types, or an enum when the set is fixed and you want exhaustive matching.
9. An integer addition overflows. What happens and how would you handle it?
Show answerHide answer
Debug builds panic and release builds wrap by default. Use checked, saturating or wrapping methods to state the behaviour you want.
10. You are asked to use unsafe for speed. How do you decide?
Show answerHide answer
First measure and try safe optimisations. If unsafe is justified, keep it small, wrap it in a safe API, document the invariants and test it with tools such as Miri.
