Traits and Generics
Traits are Rust's interfaces and generics are checked against them, with static or dynamic dispatch as a choice. Interviewers test bounds, trait objects, coherence and impl Trait.
on this pageshowhide
explore
- Defining Shared Behaviour5 questions
- Bounds and Monomorphization6 questions
- Vtables and Dynamic Dispatch5 questions
- Associated Types4 questions
- Coherence and Orphan Rule4 questions
- Opaque Impl Types6 questions
- Const Parameters and Typestate6 questions
questions
page 2 of 2In Rust, why can't an `Iterator` yield overlapping `&mut` windows into its own buffer, and how does a generic associated type `type Item<'a>` fix it?
basics
~20 sIterator's Item is fixed per impl and cannot name the lifetime of next's &mut self borrow, so items may outlive the call and overlapping &mut windows would alias. A generic associated type ties each item to that borrow.
After a dependency update, a Rust call `email.retry("disk full", 3)` that compiled before now fails with E0034 — what changed, and how do you fix it?
basics
~20 sA trait that is in scope at the call site gained a retry method, typically a new default method upstream, so two trait methods now match. Disambiguate with RetryExt::retry(&email, ...) or Notifier::retry(&email, ...), or rename your own trait's method.
In Rust, what does `fn skus(&self) -> impl Iterator<Item = u32>` in a trait declaration mean for implementors, generic callers and `dyn` use of that trait?
basics
~20 sSince Rust 1.75, impl Trait in a trait method's return is an anonymous associated type: each impl picks its own hidden type, generic callers see only the declared bounds, and the method blocks dyn use (E0038).
On stable Rust, why do `struct A<const X: f32>` and a return type `[u8; N + 1]` using a const parameter `N` both fail to compile?
basics
~20 sStable const parameters may only be integers, bool or char, so f32 is forbidden as a const parameter type. Inside a type a const parameter must stand alone, so rustc rejects the arithmetic in N + 1.
In a Rust library's typestate builder, why seal the `State` trait that bounds `RequestBuilder<S: State>`, and how does the sealing work?
basics
~20 sGive State a supertrait declared pub inside a private module and implement it only for NoUrl and HasUrl. Other crates can still use State in bounds but cannot implement it (E0277), so the builder's set of states stays closed.
Your team plans third-party Rust plugins as dynamic libraries whose entry point returns `Box<dyn Plugin>`: what does that boundary require, and what would you choose instead?
basics
~20 sRust promises no stable layout for repr(Rust) types or trait-object vtables, so a Box<dyn Plugin> crossing a separately built library needs, at minimum, the same compiler and trait crate on both sides. A C-ABI function table, WebAssembly or a process are sturdier.
showing 31–36 of 36