I am trying to learn more about const generics and how they can apply to some grid algorithms in any dimensions. Below is a snippet - how can I create an array of the size of a const generic parameter?
type Point<const N: usize> = [i32; N];
fn new_point<const N: usize>(x: i32, y: i32) -> Point<N> {
[x, y]
}
fn main() {
let point: Point<2> = new_point(1, 2);
println!("Point: {:?}", point)
}
The above results in a compiler error:
error[E0308]: mismatched types
--> src/main.rs:4:5
|
3 | fn new_point<const N: usize>(x: i32, y: i32) -> Point<N> {
| -------- expected `[i32; N]` because of return type
4 | [x, y]
| ^^^^^^ expected `N`, found `2_usize`
|
= note: expected array `[i32; N]`
found array `[i32; 2]`
Note that I am not looking for a solution using Vec<N>
. How can I initialize this generic array with some values?
Here are some ways to construct an array of arbitrary length.
You can use
std::array::from_fn
which will allow constructing an array of any size from a function computing its elements:You can construct an array with copies of a single value:
You can construct an array and then mutate it:
You can construct an array by
map
ping from another array (this used to be done as a workaround for lack offrom_fn()
):You can construct an array by using
.try_into()
to convert a slice or vector; the conversion will fail if the slice or vector is not the correct length. See the list of implementors ofTryFrom
, and look for the ones that say... for [T; N]
.