Designators

The arguments of a macro are prefixed by a dollar sign $ and type annotated with a designator:

1. macro_rules! create_function {
2. // This macro takes an argument of designator `ident` and
3. // creates a function named `$func_name`.
4. // The `ident` designator is used for variable/function names.
5. ($func_name:ident) => (
6. fn $func_name() {
7. // The `stringify!` macro converts an `ident` into a string.
8. println!("You called {:?}()",
9. stringify!($func_name));
10. }
11. )
12. }

14. // Create functions named `foo` and `bar` with the above macro.
15. create_function!(foo);
16. create_function!(bar);

18. macro_rules! print_result {
19. // This macro takes an expression of type `expr` and prints
20. // it as a string along with its result.
21. // The `expr` designator is used for expressions.
22. ($expression:expr) => (
23. // `stringify!` will convert the expression *as it is* into a string.
24. println!("{:?} = {:?}",
25. stringify!($expression),
26. $expression);
27. )
28. }

30. fn main() {
31. foo();
32. bar();

34. print_result!(1u32 + 1);

36. // Recall that blocks are expressions too!
37. print_result!({
38. let x = 1u32;

40. x * x + 2 * x - 1
41. });
42. }

This is a list of all the designators:

  • block
  • expr is used for expressions
  • ident is used for variable/function names
  • item
  • pat (pattern)
  • path
  • stmt (statement)
  • tt (token tree)
  • ty (type)