Generics and Traits
Generic code is written once and used with different types. Instead of a concrete i32, the signature of a function, struct or enum has a type parameter T, and the concrete type is substituted where the code is used. But you can do nothing with "some" type: you cannot compare it, print it or copy it. For the function body to perform an operation, you put a bound on T — you require the type to implement the trait you need.
A trait is a set of methods that different types each implement in their own way. It is closest to an interface in Java or C#, but a trait has no fields, and the implementation is written separately from the type — even for i32 or Vec<T>. A trait can provide default methods. The standard library defines traits no program can do without: Debug and Display for printing, Clone and Copy for copying, PartialEq and Ord for comparison, From and Into for conversions.
At run time generics cost nothing: the compiler creates a separate copy of the code for every concrete type. This is called monomorphization, and you pay for it in build time and program size. This topic walks generics and traits layer by layer — from a generic function to monomorphization. Trait objects (dyn), associated types, operator overloading and the orphan rule are in the neighbouring Trait Objects topic.
Topic map
- Generic Functions — the type parameter
<T>;largest<T: PartialOrd>and error E0369 without the bound; the body is checked once against its bounds, not at every substitution; type inference and the::<>syntax. - Generic Types —
Point<T>andPoint<T, U>;Option<T>andResult<T, E>as ordinary generic enums;impl<T> Point<T>versusimpl Point<f64>;PhantomDataand an object's state in its type. - Trait Basics — a trait as shared behaviour;
impl Trait for Type; the difference from Java and C# interfaces: no fields and no inheritance of data, retroactive implementation for foreign types within the orphan rule; the trait must be imported. - Default Methods — a method body right in the trait; overriding without
super; a default method calls the required methods and cannot see fields;Iteratorgives dozens of methods for onenext. - Trait Bounds —
T: Traitin angle brackets and inwhere; several bounds with+; conditional methods inimpl; blanket implementations such asToStringfor everyT: Display; the implicitSizedand?Sized. - impl Trait — in an argument it is shorthand for a generic parameter, in the return type it is one hidden concrete type chosen by the function; two branches with different types give E0308; lifetime capture in edition 2024.
- Standard Traits —
DebugandDisplay,CloneandCopy,PartialEq/Eq,PartialOrd/Ord,Hash,Default; implementFromand you getInto;TryFromfor conversions that can fail;AsReffor flexible parameters. - Monomorphization — one copy of the code per concrete type; zero cost at run time; the bill comes in build time and file size; the comparison with
dyn.
Common mistakes and traps
| Mistake | Consequence |
|---|---|
Comparing a > b in fn largest<T>(a: T, b: T) without a bound | error[E0369]: binary operation `>` cannot be applied to type `T` — you need T: PartialOrd |
Returning different iterators from the if branches of a function with -> impl Iterator | error[E0308]: `if` and `else` have incompatible types — impl Trait means one type; you need Box<dyn Trait> or your own enum |
Implementing Display for Vec<i32> | error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate — a foreign trait for a foreign type is forbidden; you need a newtype wrapper |
Implementing Into instead of From | You do not get From, while Into comes for free from From anyway; Clippy warns with its from_over_into lint |
Sorting a Vec<f64> with sort() | error[E0277]: the trait bound `f64: Ord` is not satisfied — because of NaN, f64 has only PartialOrd; you sort with sort_by and f64::total_cmp |
| Calling a trait method without importing the trait itself | error[E0599]: no method named `summarize` found … with a hint that the trait is implemented but not in scope |
| Treating generics as free in every respect | At run time they cost nothing, but every new substituted type is one more copy of the code: a longer build, a bigger file |
Why it matters in interviews
Traits and generics are the border between the junior and the middle Rust interview. At junior level you are asked what a trait is and how it differs from an interface; at middle level — bounds, impl Trait, From/Into and the price of monomorphization. A common live-coding task is to write a generic function and add exactly the bounds the compiler demands.
What interviewers usually check:
- What a trait is and how it differs from an interface in Java or C#: no fields, the implementation separate from the type, the orphan rule.
- How to write a generic function with a bound, and when to move to
whereand+. - How
impl Traitin an argument differs fromimpl Traitin the return type, and who picks the concrete type. - How
FromandIntoare related, why you implementFromspecifically, and when you needTryFrom. - Why generics are free at run time, what you pay for that, and how static dispatch differs from
dyn. - Which standard traits are derived with
derive, and which one —Display— is written by hand.