Reputation: 451
Afaik, macros in Rust are declared by the following syntax:
macro_rules! <name> {
(<pattern>) => {
<implementation>
};
}
However I found a version where the body is enclosed in parenthesis instead of braces in Rust by Example:
macro_rules! <name> {
(<pattern>) => (
<implementation>
)
}
Notice also the missing trailing semicolon. My best guess is that this has something to do with the tail recursion that this macro uses, but I what is the official difference between a macro body enclosed in parentheses vs one enclosed in braces?
Upvotes: 0
Views: 1857
Reputation: 8804
There is no difference in the definition of a macro between (..)
, [..]
, and {..}
, see the reference documentation. The syntax for the block on the right side of =>
is DelimTokenTree. I would guess the motivation for having all three variants is to allow the pattern of your macro to contain any two types of braces.
The semicolon is optional, as you can see in the MacroRules syntax. You can even use (..)
and [..]
for the outer parts of the macro.
When you invoke the macro, you can also use these three flavors, but there are restrictions how you can use each one:
When used as an item or a statement, the MacroInvocationSemi form is used where a semicolon is required at the end when not using curly braces.
Upvotes: 2
Reputation: 10474
The branches in the macro_rules
simply have to be separated by ;
. A trailing semicolon is optional there. In the formal grammar of macro_rules
, this is described by
MacroRules :
MacroRule ( ; MacroRule )* ;?
The syntax here is similar to a regex. The list of rules is at least one rule, followed by any number of semicolon-MacroRule
pairs. All this is followed by an optional semicolon.
The choice of ()
, {}
or []
actually doesn't matter at all here. All three are accepted ways to parse a DelimTokenTree
DelimTokenTree :
( TokenTree* )
| [ TokenTree* ]
| { TokenTree* }
This means that a DelimTokenTree
will be parsed the same whether it's surrounded by ()
, []
or {}
.
In particular, the macro you linked works the same with all six combinations of choice of brackets and trailing semicolons.
Upvotes: 2