Sub topic 12
Blanket Implementations
This chapter assumes you can write generic functions with trait bounds, implement a trait for a struct, and read impl<T: Bound> Type<T> blocks. If any of that is shaky, review trait bounds and generic impl blocks first.
What a blanket implementation is
A blanket implementation is a trait implementation written for a type parameter instead of a concrete type. It says: "every type T that meets these bounds implements this trait." The compiler gives the trait to all matching types, including types written later in other crates.
Compare two impl headers:
impl Describe for i32covers one type.impl<T: Debug> Describe for Tcovers every type that implementsDebug.
The second form is what makes .to_string() work on anything printable and .into() work between convertible types.
trait Describe {
fn describe(&self) -> String;
}
impl<T: std::fmt::Debug> Describe for T {
fn describe(&self) -> String {
format!("<{:?}>", self)
}
}
fn main() {
println!("{}", 42.describe());
println!("{}", "hi".describe());
println!("{}", vec![1, 2].describe());
}This prints <42>, <"hi">, and <[1, 2]>. No type has its own Describe impl. Each one qualifies because it implements Debug.
Blanket impls in the standard library
The standard library relies on this pattern heavily.
| Blanket impl | Effect |
|---|---|
| `impl<T: Display + ?Sized> ToString for T` | Every `Display` type gets `.to_string()`. |
| `impl<T, U: From<T>> Into<U> for T` | Implementing `From` gives you `Into` for free. |
| `impl<I: Iterator> IntoIterator for I` | Every iterator can be used in a `for` loop. |
| `impl<I: Iterator + ?Sized> Iterator for &mut I` | You can pass `&mut iter` where an iterator is expected. |
This is why you implement Display and From, and almost never implement ToString or Into yourself.
use std::fmt;
struct Celsius(f64);
impl fmt::Display for Celsius {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:.1}°C", self.0)
}
}
fn main() {
let t = Celsius(21.5);
let s: String = t.to_string();
println!("{s}");
}Celsius never mentions ToString. The blanket impl in std supplies it.
How the compiler picks an impl
When you call x.describe(), the compiler looks for a Describe impl whose Self type matches x. For a blanket impl, it unifies T with the type of x and then checks the bounds. If the bounds fail, the impl does not apply, and you get an error saying the method exists but its trait bounds were not satisfied.
Adding #[derive(Debug)] to Point would move it to the "yes" branch. No other code changes.
Extension traits
A common use of blanket impls is the extension trait. You define a trait with default methods, then give it an empty blanket impl. Every type that meets the bound gains the new methods.
trait IterExt: Iterator {
fn sum_squares(self) -> i64
where
Self: Sized,
Self::Item: Into<i64>,
{
self.map(|x| {
let v: i64 = x.into();
v * v
})
.sum()
}
}
impl<I: Iterator> IterExt for I {}
fn main() {
println!("{}", vec![1i32, 2, 3].into_iter().sum_squares());
println!("{}", (1..=4u8).sum_squares());
}This prints 14 and 30. Three details matter here:
trait IterExt: IteratormakesIteratora supertrait, so the default method body can callmap.Self: Sizedis needed becausemaptakesselfby value.impl<I: Iterator> IterExt for I {}has an empty body because every method has a default.
This is how crates such as itertools add methods to all iterators.
Forwarding impls for references and boxes
Blanket impls also let a wrapper type forward to the type inside it. Suppose you write a generic function that takes G: Greet, and you want to call it with Box<dyn Greet> values. Box<dyn Greet> is a different type from dyn Greet, so it needs its own impl.
trait Greet {
fn greet(&self) -> String;
}
struct En;
struct Fr;
impl Greet for En {
fn greet(&self) -> String {
"Hello".to_string()
}
}
impl Greet for Fr {
fn greet(&self) -> String {
"Bonjour".to_string()
}
}
impl<T: Greet + ?Sized> Greet for Box<T> {
fn greet(&self) -> String {
(**self).greet()
}
}
fn welcome<G: Greet>(g: G) -> String {
format!("{}!", g.greet())
}
fn main() {
let list: Vec<Box<dyn Greet>> = vec![Box::new(En), Box::new(Fr)];
for g in list {
println!("{}", welcome(g));
}
}The ?Sized bound matters. Type parameters are Sized by default, and dyn Greet is not. Without ?Sized, the impl would cover Box<En> but not Box<dyn Greet>. The standard library uses the same pattern for &T, &mut T, and Box<T>.
Coherence rules and their limits
Blanket impls are strongly restricted by two rules.
Overlap. Two impls of the same trait must never apply to the same type. After the blanket Describe impl above, writing impl Describe for String is an error, because String: Debug means both impls match. The compiler reports "conflicting implementations of trait Describe". Stable Rust has no specialization that would let the narrower impl win.
Orphan rule. You may write an impl only if the trait or the type is local to your crate. impl<T> Describe for T is legal because Describe is yours. impl<T: Debug> std::fmt::Display for T is rejected, because both the trait and the type parameter are foreign.
Gotchas
- Trait must be in scope. Extension methods only appear when the trait is imported with
use. A missing import produces "no method named ..." even though the impl exists. - References also match.
&TimplementsDebugwheneverTdoes, sodescribecan end up running withSelf = &&str. Output looks the same here, butstd::any::type_nameor aTypeIdcheck would show the difference. - Name collisions. If a type has an inherent method
describe, it wins over the trait method. If two traits in scope both providedescribefor the same type, the call is ambiguous. UseDescribe::describe(&x)to pick one. - Implicit
Sized. Add?Sizedwhen you want the impl to coverstr,[T], ordyn Trait. Methods takingselfby value still needSelf: Sized. - Bounds are all-or-nothing. The bound is checked per type. A type that implements
Debugonly inside a feature flag or a private module will not get the trait, and the error message points at the missing bound, not at the blanket impl.
Exercise
Define a trait Loud with a method loud(&self) -> String. Write a blanket impl so that every type implementing std::fmt::Display gets loud, which returns the displayed text in uppercase followed by "!". What do 5.loud() and "hey".loud() return?
Show answer
Use trait Loud { fn loud(&self) -> String; } and impl<T: std::fmt::Display + ?Sized> Loud for T { fn loud(&self) -> String { format!("{}!", self.to_string().to_uppercase()) } }. 5.loud() returns "5!" and "hey".loud() returns "HEY!". The ?Sized bound lets the impl cover str, so "hey" can call loud directly.
Exercise
You add impl<T: Debug> Describe for T to your crate, and later try to add impl Describe for Vec<u8>. Why does this fail, and what are two ways to fix it?
Show answer
Vec<u8> implements Debug, so both impls apply to it and the compiler reports conflicting implementations. One fix is to delete the specific impl and let the blanket impl cover Vec<u8>. The other is to narrow the blanket bound, for example by introducing a marker trait that Vec<u8> does not implement, or to remove the blanket impl and write per-type impls.