Macro Trait Implementation


#1

Given:

trait Foo {
    fn bar(self);
}

fn main() {
    Foo::bar(1i32);
}

We can implement Foo for i32 currently with a macro if we wish as:

macro_rules! impl_bar {
    () => (
        fn bar(self) { return () }
    );
}

impl Foo for i32 {
    impl_bar!();
}

But wouldn’t it be cool if we could do something like:

impl Foo for i32 {
    macro bar {
        (...) => (...)
    }
}

Thoughts?


#2

I didn’t see the point here. We create macros to reduce code duplication. In your case, if the macro is only for a single impl I didn’t see how it helps on reducing code.

Your example with a macro defined outside the impl block can be used to implement other trait instances. but your proposed version have the macro inside, makes it only usable inside the body. This limits its usage.