liveBook · Manning

Blanket implementation

As explained in Write Powerful Rust Macros

A blanket implementation is a trait implementation written for every type satisfying specified bounds.

A blanket implementation implements a trait for every type satisfying specified bounds. It can remove duplication, but broad behavior may make code harder to understand than an ordinary function or generic function. section 1.3.2

Listing 1.2 The powers and dangers of generics
trait Hello {
    fn hello(&self);
}

impl<T:Copy> Hello for T {
    fn hello(&self) {
        println!("Hello world");
    }
}

fn main() {
    2.hello();
    true.hello();
    'c'.hello();
}

An extension trait named Hello is implemented for every Copy type, making hello available on numbers, characters, and Booleans. section 1.3.2

Use blanket implementations carefully:

  • Prefer them when the added behavior is clear and well-defined. section 1.3.2
  • Treat them as an alternative to generic functions for avoiding duplication, not as an automatic default. section 1.3.2
  • Avoid broad implementations when readers must inspect the implementation to understand ordinary code. section 1.3.2

How Write Powerful Rust Macros covers it

How deep it goes
Demonstrates the syntax and extension-trait pattern, then stops at readability trade-offs rather than implementation internals.
Examples
Shows Hello implemented for every Copy type, then calls hello on an integer, Boolean, and character.
What it assumes
Assumes familiarity with Rust traits, generic implementation blocks, method calls, and the Copy bound.
What you can do after
Evaluate when a blanket implementation improves reuse without obscuring the behavior of ordinary Rust code.
How it connects
Connects traits, generic functions, macros, extension traits, and the Copy bound.

Also explained in

Compare how 3 books explain blanket implementation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.