Skip to main content

split_impl

Attribute Macro split_impl 

Source
#[split_impl]
Expand description

Support simultaneous definition of a trait and its implementation

Sometimes a trait is used only (or primarily) to provide an interface over a single object. In such cases, writing out the method prototypes twice (in both the trait and its implementation) should be unnecessary.

This attribute splits an implementation for a specified target off from a trait definition.

§Details

This attribute must be applied to a trait definition. This trait definition is retained with only modifications being that method implementations and #[inline] attributes are removed. An implied limitation of this attribute is that methods of the trait cannot have default implementations.

Meanwhile, an implementation of the trait is generated for the given target. This implementation uses all method implementations from the trait.

Generics may be introduced for the implementation only using syntax like #[split_impl(for<'a, T> Target<'a, T> where T: Trait)]. Implementation generics are combined with trait generics.

Specific attributes of the trait are copied to the implementation: cfg, allow, warn, deny, forbid. All trait method attributes except doc are copied to the implementation.

§Example

#[split_impl(for str)]
trait Greet {
    /// Introduce yourself
    fn greet(&self) {
        println!("Hello world, I am {self}!");
    }
}

fn main() {
    "Ferris".greet();
}