Sub topic 12
Blanket implementations
This chapter assumes you can write a trait, implement it for a type, and read a trait bound such as T: Debug. A blanket implementation uses those pieces together.
What a blanket implementation is
A blanket implementation implements a trait for every type that meets a bound, in a single impl block. The impl declares a type parameter and uses that parameter as the target type.
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());
}The output is <42>, <"hi"> and <[1, 2]>. You never wrote impl Describe for i32 or impl Describe for Vec<i32>. Any type that implements Debug now has describe, including types you define later.
Blanket impls in the standard library
The standard library uses this pattern in many places.
impl<T: Display> ToString for Tis why everyDisplaytype has.to_string().impl<T, U: From<T>> Into<U> for Tis why you usually implementFromand getIntoautomatically.impl<I: Iterator> IntoIterator for Ilets any iterator be used in aforloop.
The usual design is to ask implementors for one small trait and provide the extra methods to everyone through a blanket impl. This is also how extension traits are built.
An extension trait
trait Shout {
fn shout(&self) -> String;
}
impl<T: AsRef<str>> Shout for T {
fn shout(&self) -> String {
format!("{}!", self.as_ref().to_uppercase())
}
}
fn main() {
println!("{}", "hello".shout());
println!("{}", String::from("world").shout());
}This prints HELLO! and WORLD!. Both &str and String implement AsRef<str>, so both get shout.
Rules and common errors
Coherence rules limit blanket impls. You will hit these errors most often.
- Overlap. If
impl<T: Debug> Describe for Texists, you cannot also writeimpl Describe for String.StringimplementsDebug, so both impls apply, and the compiler reports conflicting implementations. Rust has no way to pick the more specific impl on stable. - Orphan rule. You can only write
impl<T: Bound> Trait for TifTraitis defined in your crate. Writingimpl<T: Debug> Display for Tis rejected because both the trait and the type parameter are foreign. - Future-proofing. Adding a blanket impl to a published trait is a breaking change. Downstream crates may already have implemented that trait for their own types, and those impls would then overlap.
Choosing a bound
The bound controls which types get the trait. A tight bound such as T: Debug keeps the set small and predictable. A very loose bound, or no bound at all, gives the trait to every type. That often causes method-name collisions and overlap errors later. Prefer the narrowest bound that does the job.
Exercise
Write a trait Double with a method double(&self) -> String and a blanket impl for every type that implements std::fmt::Display. It should return the value's text repeated twice. What does 7.double() return, and why does impl Double for i32 fail if you add it afterward?
Show answer
Use impl<T: std::fmt::Display> Double for T { fn double(&self) -> String { format!("{0}{0}", self) } }. Calling 7.double() returns "77". Adding impl Double for i32 fails with a conflicting implementations error, because i32 implements Display and the blanket impl already covers it.