How can I generate a long const array with values taken from a range? Bonus: 1) working with no_std, 2) without using any crates
What I would like to do:
struct A {
a: i32,
b: B
}
enum B {
One,
Two
}
const AS: [A; 1024] = [A{a: 1, b: B::One}, A{a: 2, b: B::One}, ..., A{a: 1024, b: B::One}]
The furthest I got so far is:
macro_rules! generate_list {
($($a:expr)+, $variant:expr) => {
[ $( A { a: $a, b: $variant } )* ]
}
}
const AS: [A; 1024] = generate_list!(1..1025i32, B::One);
At least one problem with this seems to be that the macro is evaluated before the range expression is expanded to a list of literals.
I'm not sure if its idiomatic, but perhaps the following might work for your use case:
Playground
I used a
while
loop, as afor
loop is currently not allowed within aconst
context asE0744
indicates.The above would generate 42 values for
AS
with an offset of0
:The Godbolt Compiler Explorer shows that it generates the same instructions as writing it out manually.