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

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

how to generate const array by macro in Rust?

问题

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

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

使用宏的方式如下:

  1. define_exps!(9);

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

英文:

I want to generate this const array:

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

by macro:

  1. 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:

  1. macro_rules! define_exps {
  2. ( $num:literal ) => {
  3. const EXPS: [i64; $num] = ::seq_macro::seq!(N in 0..$num {
  4. [
  5. #(
  6. 10_i64.pow(N),
  7. )*
  8. ]
  9. });
  10. };
  11. }
英文:

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

  1. macro_rules! define_exps {
  2. ( $num:literal ) => {
  3. const EXPS: [i64; $num] = ::seq_macro::seq!(N in 0..$num {
  4. [
  5. #(
  6. 10_i64.pow(N),
  7. )*
  8. ]
  9. });
  10. };
  11. }

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:

确定