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. }
  13. // Create functions named `foo` and `bar` with the above macro.
  14. create_function!(foo);
  15. create_function!(bar);
  16. macro_rules! print_result {
  17. // This macro takes an expression of type `expr` and prints
  18. // it as a string along with its result.
  19. // The `expr` designator is used for expressions.
  20. ($expression:expr) => (
  21. // `stringify!` will convert the expression *as it is* into a string.
  22. println!("{:?} = {:?}",
  23. stringify!($expression),
  24. $expression);
  25. )
  26. }
  27. fn main() {
  28. foo();
  29. bar();
  30. print_result!(1u32 + 1);
  31. // Recall that blocks are expressions too!
  32. print_result!({
  33. let x = 1u32;
  34. x * x + 2 * x - 1
  35. });
  36. }

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)