2

I'm writing a macro:

macro_rules! foo {
    ($(print)?) => {
        // run `println!("hello") if print is given
    }
}

Which could be called as:

  • foo!() which would do nothing

  • foo!(print) which would print hello

How do I detect if print was supplied? When I use a repetition operator I need to put a variable in. Is there some sort of empty variable I can use? ((print $print:empty)?)

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
lolad
  • 321
  • 6
  • 13

1 Answers1

1

Make separate rules for each case:

macro_rules! foo {
    () => {
        // do nothing
    };
    (print) => {
        println!("hello")
    };
}

fn main() {
    foo!(); // does nothing
    foo!(print); // prints "hello"
}

playground

pretzelhammer
  • 13,874
  • 15
  • 47
  • 98