Please help to me understand macro rules

I am new to rust, please help to me understand macro rules.

#[macro_export]
macro_rules! route {
    ($id:ident) => {
        fn [$id] () {
          $body
        }
    };
}

Function that will be transform from

fn index(ctx: Context) -> () {
    ctx
    ...
}

After Transform / Transform Into

fn index(ctx: Context) -> Pin<Box<dyn Future = ()>> {
  async move {
    ctx
    ...
  }
}

Transform

let h = route!(index);

You should be more specific about what your question is. What are you trying to achieve? Or what do you want to learn? Are you trying to create your own macro or understand an existing one? Etc…

Note that the code examples you present are rather incomplete. E.g. there’s a macro definition for route referencing a $body argument that’s not introduced. Also a transformation like the one you show for the index function can never be achieved just by calling a macro like route!(index). Macros only work syntactically with tokens you pass to them, they cannot look up e.g. a function definition of index or such things. And by the way, what is h supposed to be?

Also Pin<Box<dyn Future = ()>> is not valid syntax.

1 Like

Hi @steffahn
Thank you for your reply.
I guess you roughly understand what actually I am trying to say.
So is it possible what I am trying to achieve with macro rules ?

That doesn't appear to be the case to me. As a native speaker, I read @steffahn's reply as one that's well-meaning but indicates confusion (which I share). The errors he points out make it hard for someone familiar to Rust to understand your intention, and the rest of his reply is direct questions seeking clarification.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.