如何在Rust中使用宏生成常量数组?

huangapple go评论65阅读模式
英文:

how to generate const array by macro in Rust?

问题

你想通过宏生成这个常量数组:

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

使用宏的方式如下:

define_exps!(9);

其中参数 9 指定了数组的长度。可以通过宏来实现吗?

英文:

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?

答案1

得分: 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),
                )*
            ]
        });
    };
}
英文:

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),
                )*
            ]
        });
    };
}

huangapple
  • 本文由 发表于 2023年5月10日 22:31:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219674.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定