Blanket implementations in Rust
Implementing a trait for every type that meets a bound — an extension trait.
use std::fmt::Display;
trait Loud {
fn loud(&self) -> String;
}
impl<T: Display> Loud for T {
fn loud(&self) -> String {
format!("{}!!", self)
}
}
fn main() {
println!("{}", 42.loud());
println!("{}", "rust".loud());
println!("{}", 1.5.loud());
println!("{}", 'x'.loud());
}
How it works
impl<T: Display> Loud for Tcovers all of them at once.- This is how
ToStringreaches everything withDisplay. - Callers get the method without importing a wrapper.
Keywords and builtins used here
DisplayStringfnforimplloudmainselftraituse
The run, in numbers
- Lines
- 18
- Characters to type
- 277
- Tokens
- 108
- Three-star pace
- 110 tpm
At the three-star pace of 110 tokens a minute, this run takes about 59 seconds.
Step 2 of 3 in Dynamic dispatch, step 17 of 19 in Traits & generics.