-1

I want to match a pattern like:

foo!(1,2,3;4,5,6;7,8,9); 

The same code would be generated for all numbers, but I'd want additional code to run when there's a semi-colon. Is this sort of pattern possible?

I've tried:

macro_rule! {
    foo ($($x:expr),*);*) => ...

But I can't seem to make that work on the right-hand side.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Fuujin
  • 480
  • 5
  • 9
  • *I've tried: `macro_rule!`* — that's not how you define macros, the parenthesis aren't even matched. This question doesn't demonstrate that you've put any effort into the question before asking it. Stack Overflow isn't a service where people write code for you; please show what you've *actually* tried. Additionally, show what the macro should expand to. – Shepmaster Jan 30 '18 at 03:03
  • I'm sorry that I've upset you. Stack Overflow *does* expect a baseline of effort when asking for help: *Questions seeking debugging help ("why isn't this code working?") must include the desired behavior, a specific problem or error and the shortest code necessary to reproduce it in the question itself*, so I suppose one could call that pedantic. It's great that you realized that your original code was too big, which is why we want people to create a [MCVE]. – Shepmaster Jan 30 '18 at 16:43
  • In the future, please explain by what you mean by "I can't seem to make that work". "Not working" is the default state of things and encompasses an infinite number of possibilities, thus it isn't helpful at all to anyone else. – Shepmaster Jan 30 '18 at 16:53

1 Answers1

0

You never explained what the problem was with your existing code, so I don't know what to highlight in this example:

macro_rules! foo {
    ($($($x:expr),*);*) => {
        $(
            $(
                print!("{},", $x);
            )*
            println!("semi");
        )*
    }
}

fn main() {
    foo!(1,2,3;4,5,6;7,8,9); 
}

I can point out things from your original code:

  1. It's called macro_rules!, not macro_rule!
  2. The name of the macro being defined goes before the original {, not after.
  3. Like most programming, paired delimiters need to be evenly matched to be syntactically valid.

The Rust Programming Language, first edition has several pieces of valuable information.

Basic syntax for defining a macro is covered in the macros chapter; I strongly suggest you read the entire thing. It also links to the reference, which contains some more lower-level detail.

The section most related to your question is:

Repetition

The repetition operator follows two principal rules:

  1. $(...)* walks through one "layer" of repetitions, for all of the $names it contains, in lockstep, and
  2. each $name must be under at least as many $(...)*s as it was matched against. If it is under more, it’ll be duplicated, as appropriate.
Community
  • 1
  • 1
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366