Macro_rules logic based on optional arg

Is there anyway to return a different value based on the optional presence of an argument to macro_rules? For instance, I want an additional comma separating id from label but only if label is defined. I can achieve this with separate rules, but is there a more concise way?:

macro_rules! options {
  ($table:tt, $id:tt) => (concat!("select distinct ", $id, " from ", $table, ";"));
  ($table:tt, $id:tt, $label:tt) => (concat!("select distinct ", $id, ", ", $label, " from ", $table, ";"))

You can use the $(…)? Kleene operator. It's just like $(…)* or $(…)+, except it allows exactly 0 or 1 occurrence.



1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.