Is there a way to count with macros?

前端 未结 3 2026
后悔当初
后悔当初 2020-11-28 15:03

I want to create a macro that prints \"Hello\" a specified number of times. It\'s used like:

many_greetings!(3);  // expands to three `println!(\"Hello\");`          


        
3条回答
  •  感动是毒
    2020-11-28 15:44

    As far as I know, no. The macro language is based on pattern matching and variable substitution, and only evaluates macros.

    Now, you can implement counting with evaluation: it just is boring... see the playpen

    macro_rules! many_greetings {
        (3) => {{
            println!("Hello");
            many_greetings!(2);
        }};
        (2) => {{
            println!("Hello");
            many_greetings!(1);
        }};
        (1) => {{
            println!("Hello");
            many_greetings!(0);
        }};
        (0) => ();
    }
    

    Based on this, I am pretty sure one could invent a set of macro to "count" and invoke various operations at each step (with the count).

提交回复
热议问题