Generics and Traits
Generic functions and types, traits and default methods, bounds and `where`, `impl Trait`, standard traits, monomorphization and coherence.
15 questions
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
Meters(5), as if{}fell back toDebug:#[derive(Debug)]serves only{:?}, andDisplayis never derived, so{}here is error E0277. - ✗Expecting
5, as if a one-field tuple struct printed as its value:Metersis a separate type, and it has noDisplayuntil you implement it by hand.
Follow-up questions
- →How would you implement
Displayso that{}prints5 m? - →Why does the standard library refuse to derive
Displayfor you?
JuniorCodeCommonWrite a generic function that joins items of any printable type into a string
Write a generic function that joins items of any printable type into a string
Declare fn describe_all<T: Display>(items: &[T]) -> String: the Display bound is what lets the body call to_string() or use {} on an item. Push each item's text into a String with , between items; with no bound, to_string() is E0599.
Common mistakes
- ✗Leaving
Tunbounded and expecting the call site to supplyDisplay, as C++ templates do - ✗Bounding
TbyDebug, which prints&stritems in quotes - ✗Writing
&[dyn Display], a slice of unsized values that cannot exist
Follow-up questions
- →Where does
to_string()come from when the bound only asks forDisplay? - →How would you write the same body as one iterator chain instead of a loop?
JuniorTheoryCommonWhat happens when this program is built and run?
What happens when this program is built and run?
It does not compile
Open full question →Common mistakes
- ✗Expecting
7becausei32supports>: Rust checks a generic body once against its bounds, not per call as C++ templates do, soa > bon an unboundedTis error E0369. - ✗Expecting a panic at run time: whether
Tsupports>is decided while building, so nothing runs untilT: PartialOrdis added.
Follow-up questions
- →What is the smallest change that makes this program print
7? - →Why does the error appear even when
largestis never called?
JuniorTheoryCommonWhat does the program print?
What does the program print?
[hello]
Open full question →Common mistakes
- ✗Expecting a compile error because
impl Greet for En {}writes no methods: E0046 is raised only for a trait method with no body, andhihas a default one. - ✗Expecting the empty braces to make
hireturn nothing: a method left out of theimplkeeps the trait's default body, so it returnshello.
Follow-up questions
- →How would
Enoverridehi, and could its version still call the default body? - →Which error do you get if the body of
hiis removed from the trait?
JuniorTheoryCommonWhat is a trait in Rust, and how does it differ from a Java or C# interface?
What is a trait in Rust, and how does it differ from a Java or C# interface?
A trait is a named set of methods, some with default bodies. A type implements it in a separate impl Trait for Type block, so your trait can be added even to i32, unlike a Java class that lists its interfaces itself. A trait holds no data.
Common mistakes
- ✗Expecting a trait to declare fields that implementing types inherit, as an abstract class does
- ✗Thinking a trait can be implemented only by types declared in your own crate, so never for
i32 - ✗Believing trait methods cannot have bodies, though default methods are common
Follow-up questions
- →Why can't you implement
DisplayforVec<i32>, and how do you work around it? - →Why can a call to a trait method fail to compile until the trait is imported?
MiddleTheoryCommonWhen do you write trait bounds inline vs in where, and what is a blanket impl?
When do you write trait bounds inline vs in where, and what is a blanket impl?
fn f<T: A + B>(x: T) equals fn f<T>(x: T) where T: A + B; + demands every trait. where reads better with many bounds and can bound other types, as in Vec<T>: Debug. A blanket impl, impl<T: Display> Log for T, covers every such type.
Common mistakes
- ✗Thinking
wherechanges what a bound means rather than only where it is written - ✗Reading
T: A + Bas either trait instead of both - ✗Writing a second
implfor a type a blanket impl already covers, which is E0119
Follow-up questions
- →Why does the blanket impl of
ToStringcarry a?Sizedbound? - →What does a trait bound on an
implblock do to the methods inside it?
MiddleTheoryCommonHow are From and Into related, and when do you need TryFrom instead?
How are From and Into related, and when do you need TryFrom instead?
The std blanket impl impl<T, U: From<T>> Into<U> for T gives every From a free Into: implement From, call .into() where the target type is known. From must not fail; a fallible conversion implements TryFrom and returns Result.
Common mistakes
- ✗Implementing
Intoby hand, which gives noFromin return - ✗Calling
.into()where the target type cannot be inferred, which is E0283 - ✗Using
Fromfor a conversion that can fail, such asi32tou8
Follow-up questions
- →How does the
?operator useFromto turn one error type into another? - →What does
u8::try_from(300)return, and why is there nou8::from(300_i32)?
MiddleTheoryCommonimpl Trait as a parameter vs as a return type: who picks the concrete type?
impl Trait as a parameter vs as a return type: who picks the concrete type?
As a parameter it is shorthand for a generic T: Trait: the caller picks the type, one copy per type. As a return type the function picks one hidden concrete type; the caller sees only the trait's methods, cannot name it; every branch returns it.
Common mistakes
- ✗Treating
impl Traitas a boxed trait object with a vtable - ✗Returning two different iterator types from the branches of a function declared
-> impl Iterator - ✗Calling a method of the concrete type, such as
len, on a returnedimpl Iterator
Follow-up questions
- →Why can't you call
f::<i32>(…)when the parameter offisimpl Display? - →What does a returned
impl Traitcapture in edition 2024, and how does the precise-capturing syntaxuse<'a>narrow it?
MiddleTheoryCommonAre Rust generics zero-cost? Explain monomorphization and its price.
Are Rust generics zero-cost? Explain monomorphization and its price.
At run time, yes: the compiler monomorphizes a generic function, emitting a separate copy for every concrete type it is used with, so each call is direct and inlinable, with no boxing and no vtable. The price is longer builds and a bigger binary.
Common mistakes
- ✗Assuming Rust erases generics to one shared copy, as Java does
- ✗Calling generics free without naming the build time and binary size they cost
- ✗Thinking the per-type copies are generated at run time
Follow-up questions
- →How does a thin generic wrapper over a non-generic inner function cut code bloat?
- →When would you pick
dyn Traitover a generic despite the indirect call?
MiddleTheoryOccasionalReturning impl Trait, a generic T or Box<dyn Trait>: how do they differ?
Returning impl Trait, a generic T or Box<dyn Trait>: how do they differ?
With -> T the caller picks the type: let n: i32 = make();. With -> impl Trait the function picks one hidden type, called statically. Only -> Box<dyn Trait> can vary the type by branch, at the cost of a heap allocation and a vtable call.
Common mistakes
- ✗Thinking a generic
-> Tlets the function chooseTin its body - ✗Returning two different types from the branches of a function declared
-> impl Trait - ✗Assuming
Box<dyn Trait>costs the same asimpl Trait
Follow-up questions
- →Besides
Box<dyn Trait>, how can an enum let two branches return different iterators? - →Why does
let x = make();fail to compile whenmakereturns a genericT?
SeniorDesignOccasionalA log scanner reads a multi-gigabyte file through one reusable 64 KiB buffer. For each record it must hand the caller a mutable window, &mut [u8], into that buffer, so the caller can mask secrets in place before the buffer is refilled. Constraints: no copying and no allocation per record; each window is valid only until the next one is requested; the API should read like iteration and stay generic over the record source; safe Rust only. Explain why the standard Iterator trait cannot express this, what a generic associated type (GAT) such as type Item<'a> where Self: 'a adds, and what the resulting iterator pattern, a so-called lending iterator, still cannot do.
A log scanner reads a multi-gigabyte file through one reusable 64 KiB buffer. For each record it must hand the caller a mutable window, &mut [u8], into that buffer, so the caller can mask secrets in place before the buffer is refilled. Constraints: no copying and no allocation per record; each window is valid only until the next one is requested; the API should read like iteration and stay generic over the record source; safe Rust only. Explain why the standard Iterator trait cannot express this, what a generic associated type (GAT) such as type Item<'a> where Self: 'a adds, and what the resulting iterator pattern, a so-called lending iterator, still cannot do.
In Iterator, Item is fixed for the iterator and cannot borrow from the &mut self of each next call, so a window into its buffer is rejected. A GAT type Item<'a> where Self: 'a can, but for and std adapters do not take it.
Common mistakes
- ✗Adding a lifetime parameter to the struct and expecting
type Item = &'a mut [u8]to compile - ✗Expecting a GAT-based trait to work with
forloops andcollect - ✗Stretching the window's lifetime with
unsafe, which lets a caller hold two aliasing&mutwindows
Follow-up questions
- →Why must
type Item<'a>carry the boundwhere Self: 'a? - →How would a caller consume such an iterator with a
while letloop?
SeniorTheoryOccasionalWhat is PhantomData<T> for, and what changes if a *mut T struct omits it?
What is PhantomData<T> for, and what changes if a *mut T struct omits it?
A zero-sized field making a struct act as if it owned a T, so an unused parameter is not E0392. Beside *mut T it changes little: the struct is already invariant and not Send; the ownership mark serves drop check under #[may_dangle].
Common mistakes
- ✗Thinking
PhantomDatastores data or a type tag at run time - ✗Expecting
PhantomData<T>to free the value behind a raw pointer, so noDropimpl is written - ✗Expecting
PhantomData<T>to make a*mut Tstruct covariant orSend; std pairs it withNonNull<T>for variance
Follow-up questions
- →Which form of
PhantomDatamakes a struct invariant inT, and when do you want that? - →How does a
PhantomData<*const ()>field change theSendandSyncof a struct?
SeniorTheoryOccasionalWhat is Sized, why is it implied on generics, and what does ?Sized allow?
What is Sized, why is it implied on generics, and what does ?Sized allow?
Sized marks types with a size known at compile time. Every type parameter is implicitly T: Sized, so a T can sit on the stack and move by value. T: ?Sized lifts that to admit str, [T] or dyn Trait, but only behind &T or Box<T>.
Common mistakes
- ✗Thinking
StringorVec<T>is unsized because its data lives on the heap - ✗Expecting
fn f<T: Display>(x: &T)to accept a&strwithout?Sized - ✗Believing
?Sizedlets a function takestror[T]by value
Follow-up questions
- →Why is
SelfnotSizedby default inside a trait, and when do you addwhere Self: Sized? - →How many bytes do
&strandBox<dyn Trait>take on a 64-bit target, and why?
SeniorTheoryOccasionalWhat is trait specialization, why is it nightly-only, and what works on stable?
What is trait specialization, why is it nightly-only, and what works on stable?
Specialization lets a narrower impl override a default fn of an overlapping blanket impl. It is nightly-only (E0554 on stable): impls differing only in lifetimes make it unsound. On stable: a newtype or a shadowing inherent method.
Common mistakes
- ✗Expecting the compiler to pick the narrower of two overlapping impls, which is E0119 on stable
- ✗Confusing specialization with monomorphization
- ✗Forgetting that an inherent method shadows the trait only on concrete types, not inside generic code
Follow-up questions
- →What does the restricted feature
min_specializationgive up to stay sound? - →Why does an inherent method not shadow the blanket impl inside a generic
fn f<T: Trait>?
SeniorDesignOccasionalA database client exposes ConnectionBuilder with host(), port(), an optional timeout() and connect(). Today connect() called before host and port are set panics at run time, and code review keeps missing it. Redesign the builder so that calling connect() too early, or setting the host twice, is a compile error. Constraints: timeout stays optional and may be set at any point; host and port may be set in either order; the change adds no run-time cost and no allocation; callers keep the chained style ConnectionBuilder::new().host("db").port(5432).connect(). Describe how you encode the builder's states in the type system with the type-level state pattern typestate, and name the limits of this approach.
A database client exposes ConnectionBuilder with host(), port(), an optional timeout() and connect(). Today connect() called before host and port are set panics at run time, and code review keeps missing it. Redesign the builder so that calling connect() too early, or setting the host twice, is a compile error. Constraints: timeout stays optional and may be set at any point; host and port may be set in either order; the change adds no run-time cost and no allocation; callers keep the chained style ConnectionBuilder::new().host("db").port(5432).connect(). Describe how you encode the builder's states in the type system with the type-level state pattern typestate, and name the limits of this approach.
Make Builder<H, P> generic over zero-sized states: setters consume self into the next state, and connect() exists only in impl Builder<Host, Port>, so an early call is E0599. Limits: states are fixed at compile time; impls multiply.
Common mistakes
- ✗Calling a run-time check that returns
Resulta typestate, though the early call still compiles - ✗Assuming the state types add bytes, though zero-sized types cost nothing
- ✗Ignoring that a state chosen at run time cannot be expressed as a type
Follow-up questions
- →How would you let
timeout()be called in any state without writing it four times? - →When would you keep the state in a
PhantomDatafield instead of in the real fields?