Let's consider a function like this:
fn test<const N: usize>() -> [f64; N] {
if N == 1 {
[0.0_f64; 1]
} else if N == 2 {
[1.0_f64; 2]
} else {
panic!()
}
}
My understanding is that the compiler would evaluate the value of N at compile time. If this is the case, the if statement could also be evaluated at compile time, thus the right type should be returned since [0.0_f64; 1] is only returned if N == 1 and [1.0_f64; 2] is only returned if N == 2.
Now, when i try to compile this code, the compiler fails, basically telling me that the dimensions of the returned arrays are wrong since they do not explicitly have N as length.
I do realize, that i could implement this specific example as
fn test<const N: usize>() -> [f64; N] {
match N {
1 => { [0.0_f64; N] },
2 => { [1.0_f64; N] },
_ => { panic!("Invalid value {}", N) },
}
}
But that does not work in my actual code, since that uses different functions with fixed array sizes for the different branches.
Is there a way to do this at all? Maybe using something like the #![cfg] makro?
To clarify my why my problem does not work, let's write this out:
fn some_fct() -> [f64; 1] {
[0.0_f64; 1]
}
fn some_other_fct() -> [f64; 2] {
[1.0_f64; 2]
}
fn test<const N: usize>() -> [f64; N] {
match N {
1 => some_fct(),
2 => some_other_fct(),
_ => {
panic!("Invalid value {}", N)
}
}
}
And I cannot really write some_fct() and some_other_fct() to return with generic sizes due to other restrictions in the program structure.