How do I detect if an optional keyword was supplied to a declarative macro?

422 views Asked by At

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)?)

1

There are 1 answers

1
pretzelhammer On

Make separate rules for each case:

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

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

playground