Implementing a trait for multiple types at once

The only way to implement a trait once for many concrete types is to implement a trait for all types already implementing another trait.

For example, you can implement a marker trait Xed and then:

impl<T> Double for T
where
    T: Xed,
{
    fn double(&self) {
        /* ... */
    }
}

However, Rust has principled generics. The only thing that you know about T in the previous implementation is that T implements the Xed trait, and therefore the only associated types/functions you can use are those coming from Xed.

A trait cannot expose a field/attribute, only associated types, constants and functions, so Xed would need a getter for x (which need not be called x).

If you wish to rely on syntactic (and not semantic) properties of the code, then use macros.

Leave a Comment