Rust / Blanket Implementation
Posted On 01.20.2022
By using generic parameters, you can impl
a trait for any type that satisfies some trait bounds, for example, implement trait ToString
for every type T
that implemented the Display
trait:
impl<T: Display> ToString for T {
...
}
This technique is called blanket implementation. It’s being used widely in Rust standard library.
You can even omit the trait bound to implement your trait for every type:
mod foo {
pub trait Foo {
fn bar(&self) {
println!("Foo::Barrrrrr!!!");
}
}
impl<T> Foo for T {}
}
use foo::Foo;
let i = 10i32;
i.bar();