2

I want to generate this const array:

const EXPS: [i64; 9] = [1,
    10_i64.pow(1), 10_i64.pow(2), 10_i64.pow(3), 10_i64.pow(4),
    10_i64.pow(5), 10_i64.pow(6), 10_i64.pow(7), 10_i64.pow(8)]

by macro:

define_exps!(9);

where the argument 9 specifies the length of array.

Can I make this by macro?

Bingzheng Wu
  • 435
  • 3
  • 11

1 Answers1

4

Yes. You can do that as a procedural macro, but also as a declarative macro using dtolnay's seq-macro:

macro_rules! define_exps {
    ( $num:literal ) => {
        const EXPS: [i64; $num] = ::seq_macro::seq!(N in 0..$num {
            [
                #(
                    10_i64.pow(N),
                )*
            ]
        });
    };
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77