Sub topic 14
Blanket Implementations
A blanket implementation implements a trait for every type that satisfies a bound, instead of for one named type. This chapter assumes you can define and implement traits, write trait bounds and where clauses, and know the orphan rule from the previous chapter. It also assumes you have read the chapter on supertraits.
What a blanket implementation is
A normal implementation names a concrete type: impl Summary for Tweet. A blanket implementation uses a generic parameter in the place of the type:
use std::fmt::Display;
trait Describe {
fn describe(&self) -> String;
}
impl<T: Display> Describe for T {
fn describe(&self) -> String {
format!("<{}>", self)
}
}
fn main() {
println!("{}", 42_i32.describe());
println!("{}", 3.5_f64.describe());
println!("{}", String::from("ana").describe());
}The header impl<T: Display> Describe for T reads as "for every type T that implements Display, T implements Describe". You write the impl once. You never write impl Describe for i32 or impl Describe for String.
The program prints <42>, <3.5>, and <ana>.
A type that does not meet the bound gets no implementation. vec![1, 2].describe() fails to compile, because Vec<i32> does not implement Display. The error says the method exists but its trait bounds were not satisfied.
Blanket implementations in the standard library
You already rely on several of these:
| Blanket implementation | What it gives you |
|---|---|
| `impl<T: Display + ?Sized> ToString for T` | `.to_string()` on anything printable |
| `impl<T, U: From<T>> Into<U> for T` | `.into()` whenever `From` exists in the other direction |
| `impl<T> From<T> for T` | Every type converts to itself |
| `impl<I: Iterator + ?Sized> Iterator for &mut I` | A mutable reference to an iterator is also an iterator |
This explains a common observation. You implement Display for your type and .to_string() appears. You implement From<A> for B and .into() appears on A. In both cases the library has a blanket impl that turns the trait you wrote into the one you wanted.
Relaxing the implicit Sized bound
Every generic parameter has an implicit T: Sized bound. So impl<T: Display> Describe for T does not cover str, which is unsized. Calling "hi".describe() still works, because method lookup falls back to Self = &str. A function that takes a &str and calls describe on a str value or a dyn Display object would not work.
To cover unsized types, relax the bound with ?Sized. The method takes &self, so this is safe:
use std::fmt::Display;
trait Describe {
fn describe(&self) -> String;
}
impl<T: Display + ?Sized> Describe for T {
fn describe(&self) -> String {
format!("<{}>", self)
}
}
fn describe_dyn(item: &dyn Display) -> String {
item.describe()
}
fn main() {
println!("{}", "hi".describe());
println!("{}", describe_dyn(&7));
}The standard library writes ToString the same way, with ?Sized. Do the same in your own blanket impls unless the method needs to take self by value.
Extension traits: blanket impls over a trait
The most useful pattern is an extension trait. You add methods to every type that implements an existing trait, including traits you do not own. The supertrait gives the new methods access to the base behavior, and the blanket impl applies it everywhere:
trait IteratorExt: Iterator {
fn sum_of_squares(self) -> u64
where
Self: Sized + Iterator<Item = u64>,
{
self.map(|x| x * x).sum()
}
}
impl<I: Iterator> IteratorExt for I {}
fn main() {
let total = (1..=3u64).sum_of_squares();
println!("{total}");
}The impl body is empty because the trait has only default methods. Every iterator gets sum_of_squares, and it is callable when the item type is u64. The program prints 14.
This is how crates such as itertools add methods to Iterator. Users must import the extension trait with use before its methods appear. A trait's methods are only visible while the trait is in scope.
How the compiler checks a blanket impl
A call such as x.describe() works through ordinary method lookup and trait solving.
Blanket impls are resolved at compile time. Each concrete type that uses describe gets its own monomorphized copy, exactly as with any generic function. There is no run-time cost for the blanket form.
Coherence: overlap is an error
Coherence allows at most one applicable implementation of a trait for any type. A blanket impl covers many types at once, so it collides with any specific impl that falls inside its range.
Suppose you keep impl<T: Display> Describe for T and add impl Describe for User, where User implements Display. The compiler reports error E0119, conflicting implementations. Rust has no stable specialization, so a more specific impl cannot override a general one.
The check is stricter than you may expect:
- If
Useris your own type and does not implementDisplay, the compiler knows this and accepts a specific impl. - If the type is foreign, such as
Vec<i32>, the compiler rejects the specific impl. The reason is that the upstream crate may addDisplay for Vec<i32>in a later release. This is a deliberate guard, and it protects you from a future upgrade breaking your build.
Two blanket impls of the same trait with different bounds also conflict, such as impl<T: Display> Describe for T and impl<T: Debug> Describe for T. A type may implement both bounds, and Rust does not treat the bounds as mutually exclusive.
The usual fixes are to remove the blanket impl and implement only for specific types, or to use a newtype wrapper so the specific type is distinct. You can also split the behavior into two traits.
Blanket impls and the orphan rule
A blanket impl of your own trait is always allowed, because the trait is local. That is why impl<T: Display> Describe for T compiles even though Display and T are not yours.
A blanket impl of a foreign trait is rejected:
// Does not compile: E0210
// impl<T: MyTrait> std::fmt::Display for T { ... }Here Display is foreign and T is an uncovered type parameter, so neither is local in a way the orphan rule accepts. If this were allowed, any crate could claim a foreign trait for all types.
Gotchas
- Adding a blanket impl is a breaking change. If your library publishes a trait and later adds
impl<T: Display> Trait for T, any downstream crate that implementedTraitfor aDisplaytype now conflicts. Decide on the blanket impl before the first release. - Method name clashes. If a type has an inherent method named
describe, the inherent method wins. If two traits in scope both providedescribefor the same type, the call is ambiguous. Resolve it withDescribe::describe(&x)or<X as Describe>::describe(&x). - Large reach. A bound like
T: Displaymatches thousands of types, so a short method name on a blanket trait can appear in autocomplete everywhere. Give blanket traits specific method names and keep them out of the prelude of your own crate. - No opt-out. Once the blanket impl exists, a type cannot decline it. If some
Displaytype needs different behavior, the blanket design is wrong for that trait.
When to choose a blanket impl
Use one when the behavior can be written entirely from another trait's methods. to_string from Display and describe above are of this kind. If every implementor would write the same body, a blanket impl removes the repetition.
Use per-type impls, or default methods on the trait, when types need different behavior. A default method lets each type override the code. A blanket impl does not.
Exercise
You publish a crate with trait Label { fn label(&self) -> String; } and impl<T: Display> Label for T. A user of your crate writes impl Label for MyId where MyId is their own type with a Display impl. What happens, and why?
Show answer
Their crate fails to compile with E0119 (conflicting implementations). MyId implements Display, so your blanket impl already covers it, and coherence allows only one Label impl per type. They can wrap MyId in a newtype that does not implement Display, or you can avoid the blanket impl.
Exercise
Write an extension trait Shout with a method shout(&self) -> String that returns the Display text in upper case, and implement it for every type that implements Display, including str.
Show answer
trait Shout {
fn shout(&self) -> String;
}
impl<T: std::fmt::Display + ?Sized> Shout for T {
fn shout(&self) -> String {
self.tostring().touppercase()
}
}
The ?Sized bound is what makes "hello".shout() work on str itself, and to_string is itself provided by a blanket impl over Display.