英文:
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),
)*
]
});
};
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论