Overload

Macros can be overloaded to accept different combinations of arguments.
In that regard, macro_rules! can work similarly to a match block:

  1. // `test!` will compare `$left` and `$right`
  2. // in different ways depending on how you invoke it:
  3. macro_rules! test {
  4. // Arguments don't need to be separated by a comma.
  5. // Any template can be used!
  6. ($left:expr; and $right:expr) => (
  7. println!("{:?} and {:?} is {:?}",
  8. stringify!($left),
  9. stringify!($right),
  10. $left && $right)
  11. );
  12. // ^ each arm must end with a semicolon.
  13. ($left:expr; or $right:expr) => (
  14. println!("{:?} or {:?} is {:?}",
  15. stringify!($left),
  16. stringify!($right),
  17. $left || $right)
  18. );
  19. }
  20. fn main() {
  21. test!(1i32 + 1 == 2i32; and 2i32 * 2 == 4i32);
  22. test!(true; or false);
  23. }