typestar

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

  1. impl<T: Display> Loud for T covers all of them at once.
  2. This is how ToString reaches everything with Display.
  3. Callers get the method without importing a wrapper.

Keywords and builtins used here

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.

Type this snippet

Step 2 of 3 in Dynamic dispatch, step 17 of 19 in Traits & generics.

← Previous Next →