Skip to content

Introduce #[trait_alias] macro to simplify definition of alias traits#79

Merged
soareschen merged 15 commits intomainfrom
trait-alias
Mar 9, 2025
Merged

Introduce #[trait_alias] macro to simplify definition of alias traits#79
soareschen merged 15 commits intomainfrom
trait-alias

Conversation

@soareschen
Copy link
Collaborator

@soareschen soareschen commented Mar 2, 2025

Summary

This PR introduces a new #[trait_alias] macro, that can be used to simplify the definition of alias traits with blanket implementations. Using the macro, the blanket implementation would be derived automatically, thereby saving up to 50% or more code for the trait alias definition.

Example

The HasAsyncErrorType trait is now defined as follows:

#[trait_alias]
pub trait HasAsyncErrorType: Async + HasErrorType<Error: Async> {}

The macro now expands the following blanket implementation automatically:

impl<Context> HasAsyncErrorType for Context 
where
    Context: Async + HasErrorType<Error: Async> {}

Associated Items

The #[trait_alias] macro can also be used to automatically derive associated types and methods. For example:

#[trait_alias]
pub trait HasFooAtBar: HasFooAt<Bar, Foo = Self::FooBar> {
    type FooBar: Clone;
}

would generate the blanket impl:

impl<Context, FooBar> HasFooAtBar for Context
where
    Context: HasFooAt<Bar, Foo = FooBar>,
    FooBar: Clone,
{
    type FooBar = FooBar;
}

And given the following:

#[trait_alias]
pub trait CanDoFooBar: CanDoFoo + CanDoBar {
    fn foo_bar(&self) {
        self.foo().bar();
    }
}

Would be desugared into:

pub trait CanDoFooBar: CanDoFoo + CanDoBar {
    fn foo_bar(&self);
}

impl<Context> CanDoFooBar for Context
where
    Context: CanDoFoo + CanDoBar,
{
    fn foo_bar(&self) {
        self.foo().bar();
    }
}

@soareschen soareschen marked this pull request as ready for review March 9, 2025 21:24
@soareschen soareschen merged commit bd315a3 into main Mar 9, 2025
5 checks passed
@soareschen soareschen deleted the trait-alias branch March 9, 2025 21:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant