Macro like function to impl

fn main() {
    let foo = Foo;

    foo.bar!(1, 2, 3);
    foo.bar!(1);
}

pub struct Foo;

impl Foo {
    macro fn bar {
        ($($x:ident),+) => {{
            ...
        }}
    }
}

Seems cool :)

It’s not very easy… see e.g. here for lengthy discussion of a similar topic. Making a macro truly associated to a type is even harder, as it goes against the current evaluation model (macro expansion happens much earlier in compilation than when type information becomes available).

1 Like

I think there is some differents in your link with my post.

In my sample code, it just simply generates some function, not meant to call the macros.

foo.bar_i32_i32_i32(1,2,3);
foo.bar_i32(1);

Seems quite straight forward.

And where does the function foo_i32_i32_i32 come from?

1 Like

Generates by the macro fn bar

I think the expanding could happen when the call foo.bar!(1,2,3) happens.

Just replaced with the expanded code in place.

So it is calling a macro, effectively…

Anyway, as I mentioned above, this is not simple:

as it goes against the current evaluation model (macro expansion happens much earlier in compilation than when type information becomes available)

… and the lengthy discussion I’ve linked contains much mention of “type-based dispatch”. Including a relatively recent comment here addressing the concept of type-based dispatching of macros in general, which says

I’m fairly certain that the feature idea you show here fits sufficiently well into this field of “type-based dispatch” of macros that this comment fully applies.

2 Likes